当前位置:Gxlcms > 数据库问题 > 使用Spring AOP实现MySQL数据库读写分离案例分析

使用Spring AOP实现MySQL数据库读写分离案例分析

时间:2021-07-01 10:21:17 帮助过:15人阅读

技术图片

一、前言

分布式环境下数据库的读写分离策略是解决数据库读写性能瓶颈的一个关键解决方案,更是最大限度了提高了应用中读取 (Read)数据的速度和并发量。

在进行数据库读写分离的时候,我们首先要进行数据库的主从配置,最简单的是一台Master和一台Slave(大型网站系统的话,当然会很复杂,这里只是分析了最简单的情况)。通过主从配置主从数据库保持了相同的数据,我们在进行读操作的时候访问从数据库Slave,在进行写操作的时候访问主数据库Master。这样的话就减轻了一台服务器的压力。

在进行读写分离案例分析的时候。首先,配置数据库的主从复制,可以选择下面的这个方法:

MySQL5.6 数据库主从(Master/Slave)同步安装与配置详解

当然,只是简单的为了看一下如何用代码的方式实现数据库的读写分离,完全不必要去配置主从数据库,只需要两台安装了 相同数据库的机器就可以了。

二、实现读写分离的两种方法

具体到开发中,实现读写分离常用的有两种方式:

  • 第一种方式是我们最常用的方式,就是定义2个数据库连接,一个是MasterDataSource,另一个是SlaveDataSource。更新数据时我们读取MasterDataSource,查询数据时我们读取SlaveDataSource。这种方式很简单,我就不赘述了。
  • 第二种方式动态数据源切换,就是在程序运行时,把数据源动态织入到程序中,从而选择读取主库还是从库。主要使用的技术是:Annotation,Spring AOP ,反射。

下面会详细的介绍实现方式。

三、Aop实现主从数据库的读写分离案例

1、项目代码地址

目前该Demo的项目地址在开源中国 码云 上边:http://git.oschina.net/xuliugen/aop-choose-db-demo

技术图片

2、项目结构

技术图片

上图中,除了标记的代码,其他的主要是配置代码和业务代码。

3、具体分析

该项目是SSM框架的一个demo,Spring、Spring MVC和MyBatis,具体的配置文件不在过多介绍。

(1)UserContoller模拟读写数据

<pre style="margin: 0px; padding: 0px; border: 0px; font: inherit; vertical-align: baseline; word-break: break-word;">

  1. <code>/**
  2. * Created by xuliugen on 2016/5/4.
  3. */
  4. @Controller
  5. @RequestMapping(value = "/user", produces = {"application/json;charset=UTF-8"})
  6. public class UserController {
  7. @Inject
  8. private IUserService userService;
  9. //http://localhost:8080/user/select.do
  10. @ResponseBody
  11. @RequestMapping(value = "/select.do", method = RequestMethod.GET)
  12. public String select() {
  13. User user = userService.selectUserById(123);
  14. return user.toString();
  15. }
  16. //http://localhost:8080/user/add.do
  17. @ResponseBody
  18. @RequestMapping(value = "/add.do", method = RequestMethod.GET)
  19. public String add() {
  20. boolean isOk = userService.addUser(new User("333", "444"));
  21. return isOk == true ? "shibai" : "chenggong";
  22. }
  23. }</code>

模拟读写数据,调用IUserService 。

(2)spring-db.xml读写数据源配置

<pre style="margin: 0px; padding: 0px; border: 0px; font: inherit; vertical-align: baseline; word-break: break-word;">

  1. <code><?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  6. <bean id="statFilter" class="com.alibaba.druid.filter.stat.StatFilter" lazy-init="true">
  7. <property name="logSlowSql" value="true"/>
  8. <property name="mergeSql" value="true"/>
  9. </bean>
  10. <!-- 数据库连接 -->
  11. <bean id="readDataSource" class="com.alibaba.druid.pool.DruidDataSource"
  12. destroy-method="close" init-method="init" lazy-init="true">
  13. <property name="driverClassName" value="${driver}"/>
  14. <property name="url" value="${url1}"/>
  15. <property name="username" value="root"/>
  16. <property name="password" value="${password}"/>
  17. <!-- 省略部分内容 -->
  18. </bean>
  19. <bean id="writeDataSource" class="com.alibaba.druid.pool.DruidDataSource"
  20. destroy-method="close" init-method="init" lazy-init="true">
  21. <property name="driverClassName" value="${driver}"/>
  22. <property name="url" value="${url}"/>
  23. <property name="username" value="root"/>
  24. <property name="password" value="${password}"/>
  25. <!-- 省略部分内容 -->
  26. </bean>
  27. <!-- 配置动态分配的读写 数据源 -->
  28. <bean id="dataSource" class="com.xuliugen.choosedb.demo.aspect.ChooseDataSource" lazy-init="true">
  29. <property name="targetDataSources">
  30. <map key-type="java.lang.String" value-type="javax.sql.DataSource">
  31. <!-- write -->
  32. <entry key="write" value-ref="writeDataSource"/>
  33. <!-- read -->
  34. <entry key="read" value-ref="readDataSource"/>
  35. </map>
  36. </property>
  37. <property name="defaultTargetDataSource" ref="writeDataSource"/>
  38. <property name="methodType">
  39. <map key-type="java.lang.String">
  40. <!-- read -->
  41. <entry key="read" value=",get,select,count,list,query"/>
  42. <!-- write -->
  43. <entry key="write" value=",add,create,update,delete,remove,"/>
  44. </map>
  45. </property>
  46. </bean>
  47. </beans>
  48. </code>

上述配置中,配置了readDataSource和writeDataSource两个数据源,但是交给SqlSessionFactoryBean进行管理的只有dataSource,其中使用到了:com.xuliugen.choosedb.demo.aspect.ChooseDataSource 这个是进行数据库选择的。

<pre style="margin: 0px; padding: 0px; border: 0px; font: inherit; vertical-align: baseline; word-break: break-word;">

  1. <code><property name="methodType">
  2. <map key-type="java.lang.String">
  3. <!-- read -->
  4. <entry key="read" value=",get,select,count,list,query"/>
  5. <!-- write -->
  6. <entry key="write" value=",add,create,update,delete,remove,"/>
  7. </map>
  8. </property>
  9. </code>

配置了数据库具体的那些是读哪些是写的前缀关键字。ChooseDataSource的具体代码如下:

(3)ChooseDataSource

<pre style="margin: 0px; padding: 0px; border: 0px; font: inherit; vertical-align: baseline; word-break: break-word;">

  1. <code>/**
  2. * 获取数据源,用于动态切换数据源
  3. */
  4. public class ChooseDataSource extends AbstractRoutingDataSource {
  5. public static Map<String, List<String>> METHOD_TYPE_MAP = new HashMap<String, List<String>>();
  6. /**
  7. * 实现父类中的抽象方法,获取数据源名称
  8. * @return
  9. */
  10. protected Object determineCurrentLookupKey() {
  11. return DataSourceHandler.getDataSource();
  12. }
  13. // 设置方法名前缀对应的数据源
  14. public void setMethodType(Map<String, String> map) {
  15. for (String key : map.keySet()) {
  16. List<String> v = new ArrayList<String>();
  17. String[] types = map.get(key).split(",");
  18. for (String type : types) {
  19. if (StringUtils.isNotBlank(type)) {
  20. v.add(type);
  21. }
  22. }
  23. METHOD_TYPE_MAP.put(key, v);
  24. }
  25. }
  26. }
  27. </code>

(4)DataSourceAspect进行具体方法的AOP拦截

<pre style="margin: 0px; padding: 0px; border: 0px; font: inherit; vertical-align: baseline; word-break: break-word;">

  1. <code>/**
  2. * 切换数据源(不同方法调用不同数据源)
  3. */
  4. @Aspect
  5. @Component
  6. @EnableAspectJAutoProxy(proxyTargetClass = true)
  7. public class DataSourceAspect {
  8. protected Logger logger = LoggerFactory.getLogger(this.getClass());
  9. @Pointcut("execution(* com.xuliugen.choosedb.demo.mybatis.dao.*.*(..))")
  10. public void aspect() {
  11. }
  12. /**
  13. * 配置前置通知,使用在方法aspect()上注册的切入点
  14. */
  15. @Before("aspect()")
  16. public void before(JoinPoint point) {
  17. String className = point.getTarget().getClass().getName();
  18. String method = point.getSignature().getName();
  19. logger.info(className + "." + method + "(" + StringUtils.join(point.getArgs(), ",") + ")");
  20. try {
  21. for (String key : ChooseDataSource.METHOD_TYPE_MAP.keySet()) {
  22. for (String type : ChooseDataSource.METHOD_TYPE_MAP.get(key)) {
  23. if (method.startsWith(type)) {
  24. DataSourceHandler.putDataSource(key);
  25. }
  26. }
  27. }
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. </code>

(5)DataSourceHandler,数据源的Handler类

<pre style="margin: 0px; padding: 0px; border: 0px; font: inherit; vertical-align: baseline; word-break: break-word;">

  1. <code>package com.xuliugen.choosedb.demo.aspect;
  2. /**
  3. * 数据源的Handler类
  4. */
  5. public class DataSourceHandler {
  6. // 数据源名称线程池
  7. public static final ThreadLocal<String> holder = new ThreadLocal<String>();
  8. /**
  9. * 在项目启动的时候将配置的读、写数据源加到holder中
  10. */
  11. public static void putDataSource(String datasource) {
  12. holder.set(datasource);
  13. }
  14. /**
  15. * 从holer中获取数据源字符串
  16. */
  17. public static String getDataSource() {
  18. return holder.get();
  19. }
  20. }
  21. </code>

主要代码,如上所述。

使用Spring AOP实现MySQL数据库读写分离案例分析

标签:produce   sele   过多   min   pes   应用   padding   encoding   SSM框架   

人气教程排行