在现在互联网系统中,随着用户量的增长,单数据源通常无法满足系统的负载要求。因此为了解决用户量增长带来的压力,在数据库层面会采用读写分离技术和数据库拆分等技术。读写分离就是就是一个Master数据库,多个Slave数据库,Master数据库负责数据的写操作,slave库负责数据读操作,通过slave库来降低Master库的负载。因为在实际的应用中,数据库都是读多写少(读取数据的频率高,更新数据的频率相对较少),而读取数据通常耗时比较长,占用数据库服务器的CPU较多,从而影响用户体验。我们通常的做法就是把查询从主库中抽取出来,采用多个从库,使用负载均衡,减轻每个从库的查询压力。同时随着业务的增长,会对数据库进行拆分,根据业务将业务相关的数据库表拆分到不同的数据库中。不管是读写分离还是数据库拆分都是解决数据库压力的主要方式之一。本篇文章主要讲解Spring如何配置读写分离和多数据源手段。

1.读写分离  

  具体到开发中,如何方便的实现读写分离呢?目前常用的有两种方式:

  1. 第一种方式是最常用的方式,就是定义2个数据库连接,一个是MasterDataSource,另一个是SlaveDataSource。对数据库进行操作时,先根据需求获取dataSource,然后通过dataSource对数据库进行操作。这种方式配置简单,但是缺乏灵活新。
  2. 第二种方式动态数据源切换,就是在程序运行时,把数据源动态织入到程序中,从而选择读取主库还是从库。主要使用的技术是:annotation,Spring AOP ,反射。下面会详细的介绍实现方式。 

  在介绍实现方式之前,先准备一些必要的知识,spring的AbstractRoutingDataSource类。AbstractRoutingDataSource这个类是spring2.0以后增加的,我们先来看下AbstractRoutingDataSource的定义:

  1. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}

  AbstractRoutingDataSource继承了AbstractDataSource并实现了InitializingBean,因此AbstractRoutingDataSource会在系统启动时自动初始化实例。

  1. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
  2. private Map<Object, Object> targetDataSources;
  3. private Object defaultTargetDataSource;
  4. private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
  5. private Map<Object, DataSource> resolvedDataSources;
  6. private DataSource resolvedDefaultDataSource;
  7. ...
  8. }

  AbstractRoutingDataSource继承了AbstractDataSource ,而AbstractDataSource 又是DataSource 的子类。DataSource 是javax.sql 的数据源接口,定义如下:

  1. public interface DataSource extends CommonDataSource,Wrapper {
  2. Connection getConnection() throws SQLException;
  3. Connection getConnection(String username, String password)
  4. throws SQLException;
  5. }

  DataSource接口定义了2个方法,都是获取数据库连接。我们在看下AbstractRoutingDataSource如何实现了DataSource接口:

  1. public Connection getConnection() throws SQLException {
  2. return determineTargetDataSource().getConnection();
  3. }
  4.  
  5. public Connection getConnection(String username, String password) throws SQLException {
  6. return determineTargetDataSource().getConnection(username, password);
  7. }

  很显然就是调用自己的determineTargetDataSource() 方法获取到connection。determineTargetDataSource方法定义如下:

  1. protected DataSource determineTargetDataSource() {
  2. Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
  3. Object lookupKey = determineCurrentLookupKey();
  4. DataSource dataSource = this.resolvedDataSources.get(lookupKey);
  5. if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
  6. dataSource = this.resolvedDefaultDataSource;
  7. }
  8. if (dataSource == null) {
  9. throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
  10. }
  11. return dataSource;
  12. }

  我们最关心的还是下面2句话: 

  1. Object lookupKey = determineCurrentLookupKey();
  2. DataSource dataSource = this.resolvedDataSources.get(lookupKey);

  determineCurrentLookupKey方法返回lookupKey,resolvedDataSources方法就是根据lookupKey从Map中获得数据源。resolvedDataSources 和determineCurrentLookupKey定义如下:

  1. private Map<Object, DataSource> resolvedDataSources;
  2. protected abstract Object determineCurrentLookupKey()

  看到以上定义,我们是不是有点思路了,resolvedDataSources是Map类型,我们可以把MasterDataSource和SlaveDataSource存到Map中。通过写一个类DynamicDataSource继承AbstractRoutingDataSource,实现其determineCurrentLookupKey() 方法,该方法返回Map的key,master或slave。

  1. public class DynamicDataSource extends AbstractRoutingDataSource{
  2. @Override
  3. protected Object determineCurrentLookupKey() {
  4. return DatabaseContextHolder.getCustomerType();
  5. }
  6. }

  定义DatabaseContextHolder

  1. public class DatabaseContextHolder {
  2. private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
  3. public static void setCustomerType(String customerType) {
  4. contextHolder.set(customerType);
  5. }
  6. public static String getCustomerType() {
  7. return contextHolder.get();
  8. }
  9. public static void clearCustomerType() {
  10. contextHolder.remove();
  11. }
  12. }

  从DynamicDataSource 的定义看出,他返回的是DynamicDataSourceHolder.getDataSouce()值,我们需要在程序运行时调用DynamicDataSourceHolder.putDataSource()方法,对其赋值。下面是我们实现的核心部分,也就是AOP部分,DataSourceAspect定义如下:

  1. @Aspect
  2. @Order(1)
  3. @Component
  4. public class DataSourceAspect {
  5. @Before(value = "execution(* com.netease.nsip.DynamicDataSource.dao..*.insert*(..))"
  6. + "||execution(* com.netease.nsip.DynamicDataSource.dao..*.add*(..))"
  7. + "||@org.springframework.transaction.annotation.Transactional * *(..)")
  8. public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
  9. DatabaseContextHolder.setCustomerType("master");
  10. Object object = joinPoint.proceed();
  11. DatabaseContextHolder.setCustomerType("slave");
  12. return object;
  13. }
  14. }

  为了方便测试,我定义了2个数据库,Master库和Slave库,两个库中person表结构一致,但数据不同,properties文件配置如下:

  1. #common
  2. db-driver=com.mysql.jdbc.Driver
  3.  
  4. #master
  5. master-url=jdbc:mysql://127.0.0.1:3306/master?serverTimezone=UTC
  6. master-user=root
  7. master-password=root
  8.  
  9. #salve
  10. slave-url=jdbc:mysql://127.0.0.1:3306/slave?serverTimezone=UTC
  11. slave-user=root
  12. slave-password=root

  Spring中的xml定义如下:

  1. <!-- 配置数据源公共参数 -->
  2. <bean name="baseDataSource"
  3. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  4. <property name="driverClassName">
  5. <value>${db-driver}</value>
  6. </property>
  7. </bean>
  8.  
  9. <!-- 配置主数据源 -->
  10. <bean name="masterDataSource"
  11. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  12. <property name="url">
  13. <value>${master-url}</value>
  14. </property>
  15. <property name="username">
  16. <value>${master-user}</value>
  17. </property>
  18. <property name="password">
  19. <value>${master-password}</value>
  20. </property>
  21. </bean>
  22.  
  23. <!--配置从数据源 -->
  24. <bean name="slavueDataSource"
  25. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  26. <property name="url">
  27. <value>${slave-url}</value>
  28. </property>
  29. <property name="username">
  30. <value>${slave-user}</value>
  31. </property>
  32. <property name="password">
  33. <value>${slave-password}</value>
  34. </property>
  35. </bean>
  36.  
  37. <bean id="dataSource"
  38. class="com.netease.nsip.DynamicDataSource.commom.DynamicDataSource">
  39. <property name="targetDataSources">
  40. <map key-type="java.lang.String">
  41. <entry key="master" value-ref="masterDataSource" />
  42. <entry key="slave" value-ref="slavueDataSource" />
  43. </map>
  44. </property>
  45. <property name="defaultTargetDataSource" ref="slavueDataSource" />
  46. </bean>
  47.  
  48. <!-- 配置SqlSessionFactoryBean -->
  49. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  50. <property name="configLocation" value="classpath:SqlMapConfig.xml" />
  51. <property name="dataSource" ref="dataSource" />
  52. </bean>
  53.  
  54. <!-- 持久层访问模板化的工具,线程安全,构建sqlSessionFactory -->
  55. <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
  56. <constructor-arg index="0" ref="sqlSessionFactory" />
  57. </bean>
  58.  
  59. <!-- 事务管理器 -->
  60. <bean id="txManager"
  61. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  62. <property name="dataSource" ref="dataSource" />
  63. </bean>
  64.  
  65. <tx:annotation-driven transaction-manager="txManager"
  66. proxy-target-class="true" order="200" />
  67.  
  68. <!-- 回滚方式 -->
  69. <tx:advice id="txAdvice" transaction-manager="txManager">
  70. <tx:attributes>
  71. <tx:method name="*" rollback-for="Throwable" />
  72. </tx:attributes>
  73. </tx:advice>
  74.  
  75. <!-- 定义@Transactional的注解走事务管理器 -->
  76. <aop:config>
  77. <aop:pointcut id="transactionPointcutType"
  78. expression="@within(org.springframework.transaction.annotation.Transactional)" />
  79. <aop:pointcut id="transactionPointcutMethod"
  80. expression="@annotation(org.springframework.transaction.annotation.Transactional)" />
  81. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcutType" />
  82. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcutMethod" />
  83. </aop:config>

  到目前读写分离已经配置好了,所有的以insert和add开头的dao层,以及带有Transaction注解的会走主库,其他的数据库操作走从库。当然也可以修改切入点表达式让update和delete方法走主库。上述方法是基于AOP的读写分离配置,下面使用实例结合注解讲述多数据源的配置。

2.多数据源配置

  上面的实例使用AOP来配置读写分离,接下来将结合Spring注解配置多数据源,该方法也可以用于配置读写分离。先看下annotation的定义:

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface Profile {
  4. String value();
  5. }

  定义MultiDataSourceAspect ,在MultiDataSourceAspect根据注解获取数据源.

  1. public class MultiDataSourceAspect {
  2. public void before(JoinPoint joinPoint) throws Throwable {
  3. Object target = joinPoint.getTarget();
  4. String method = joinPoint.getSignature().getName();
  5. Class<?>[] classz = target.getClass().getInterfaces();
  6.  
  7. Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).
  8. getMethod().getParameterTypes();
  9. try {
  10. Method m = classz[0].getMethod(method, parameterTypes);
  11. if (m != null&&m.isAnnotationPresent(Profile.class)) {
  12. Profile data = m .getAnnotation(Profile.class);
  13. DatabaseContextHolder.setCustomerType(data.value());
  14. }
  15. } catch (Exception e) {
  16. }
  17. }
  18. }  

  同样为了测试,数据源properties文件如下:

  1. #common
  2. db-driver=com.mysql.jdbc.Driver
  3.  
  4. #master
  5. account-url=jdbc:mysql://127.0.0.1:3306/master?serverTimezone=UTC
  6. account-user=root
  7. account-password=root
  8.  
  9. #salve
  10. goods-url=jdbc:mysql://127.0.0.1:3306/slave?serverTimezone=UTC
  11. goods-user=root
  12. goods-password=root 

  Spring的XML文件定义如下:

  1. <!-- 配置数据源公共参数 -->
  2. <bean name="baseDataSource"
  3. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  4. <property name="driverClassName">
  5. <value>${db-driver}</value>
  6. </property>
  7. </bean>
  8.  
  9. <!-- 配置主数据源 -->
  10. <bean name="accountDataSource"
  11. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  12. <property name="url">
  13. <value>${account-url}</value>
  14. </property>
  15. <property name="username">
  16. <value>${account-user}</value>
  17. </property>
  18. <property name="password">
  19. <value>${account-password}</value>
  20. </property>
  21. </bean>
  22.  
  23. <!--配置从数据源 -->
  24. <bean name="goodsDataSource"
  25. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  26. <property name="url">
  27. <value>${goods-url}</value>
  28. </property>
  29. <property name="username">
  30. <value>${goods-user}</value>
  31. </property>
  32. <property name="password">
  33. <value>${goods-password}</value>
  34. </property>
  35. </bean>
  36.  
  37. <bean id="dataSource"
  38. class="com.netease.nsip.DynamicDataSource.commom.MultiDataSource">
  39. <property name="targetDataSources">
  40. <map key-type="java.lang.String">
  41. <entry key="goods" value-ref="goodsDataSource" />
  42. <entry key="account" value-ref="accountDataSource" />
  43. </map>
  44. </property>
  45. </bean>
  46.  
  47. <!-- 配置SqlSessionFactoryBean -->
  48. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  49. <property name="configLocation" value="classpath:multiSqlMapConfig.xml" />
  50. <property name="dataSource" ref="dataSource" />
  51. </bean>
  52.  
  53. <!-- 持久层访问模板化的工具,线程安全,构建sqlSessionFactory -->
  54. <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
  55. <constructor-arg index="0" ref="sqlSessionFactory" />
  56. </bean>
  57.  
  58. <!-- 配置AOP -->
  59. <bean id="multiAspect"
  60. class="com.netease.nsip.DynamicDataSource.commom.MultiDataSourceAspect" />
  61. <aop:config>
  62. <aop:aspect id="datasourceAspect" ref="multiAspect">
  63. <aop:pointcut
  64. expression="execution(* com.netease.nsip.DynamicDataSource.dao..*.insert*(..))"
  65. id="tx" />
  66. <aop:before pointcut-ref="tx" method="before" />
  67. </aop:aspect>
  68. </aop:config>

  dao层接口定义如下:

  1. public interface IAccountDao {
  2. @Profile("account")
  3. public boolean insert(Accounts accounts);
  4. }
  5.  
  6. public interface IGoodsDao {
  7. @Profile("goods")
  8. public boolean insert(Goods goods);
  9. }

  Spring配置多数据源的主要方式如上所示,在实例中为了方便数据源的选择都在dao进行。而在日常开发的过程中事务通常在Service层,而事务又和数据源绑定,所以为了在Service层使用事务可以将数据源的选择在service层进行。

Spring配置动态数据源-读写分离和多数据源的更多相关文章

  1. 基于spring的aop实现读写分离与事务配置

    项目开发中经常会遇到读写分离等多数据源配置的需求,在Java项目中可以通过Spring AOP来实现多数据源的切换. 一.Spring事务开启流程 Spring中通常通过@Transactional来 ...

  2. Mybatis多数据源读写分离(注解实现)

    #### Mybatis多数据源读写分离(注解实现) ------ 首先需要建立两个库进行测试,我这里使用的是master_test和slave_test两个库,两张库都有一张同样的表(偷懒,喜喜), ...

  3. Mysql主从配置,实现读写分离

    大型网站为了软解大量的并发访问,除了在网站实现分布式负载均衡,远远不够.到了数据业务层.数据访问层,如果还是传统的数据结构,或者只是单单靠一台服务器扛,如此多的数据库连接操作,数据库必然会崩溃,数据丢 ...

  4. 黄聪:Mysql主从配置,实现读写分离

    大型网站为了软解大量的并发访问,除了在网站实现分布式负载均衡,远远不够.到了数据业务层.数据访问层,如果还是传统的数据结构,或者只是单单靠一台服务器扛,如此多的数据库连接操作,数据库必然会崩溃,数据丢 ...

  5. 使用Spring配置动态数据源实现读写分离

    最近搭建的一个项目需要实现数据源的读写分离,在这里将代码进行分享,以供参考.关键词:DataSource .AbstractRoutingDataSource.AOP 首先是配置数据源 <!-- ...

  6. 阿里P7教你如何使用 Spring 配置动态数据源实现读写分离

    最近搭建的一个项目需要实现数据源的读写分离,在这里将代码进行分享,以供参考. 关键词:DataSource .AbstractRoutingDataSource.AOP 首先是配置数据源 <!- ...

  7. spring项目配置双数据源读写分离

    我们最早做新项目的时候一直想做数据库的读写分离与主从同步,由于一些原因一直没有去做这个事情,这次我们需要配置双数据源的起因是因为我们做了一个新项目用了另一个数据库,需要把这个数据库的数据显示到原来的后 ...

  8. 【Spring】Spring如何实现多数据源读写分离?这是我看过最详细的一篇!!

    写在前面 很多小伙伴私聊我说:最近他们公司的业务涉及到多个数据源的问题,问我Spring如何实现多数据源的问题.回答这个问题之前,首先需要弄懂什么是多数据源:多数据源就是在同一个项目中,会连接两个甚至 ...

  9. spring mongodb 复制集配置(实现读写分离)

    注:mongodb当前版本是3.4.3   spring连接mongodb复制集的字符串格式: mongodb://[username:password@]host1[:port1][,host2[: ...

随机推荐

  1. Jmeter5 实现多机集群压测(局域网组成多机集群)

    想要模拟高并发用户访问的场景,用Jmeter5实现的话,单靠一台PC机,资源是不够的,包括单机的内存.使用端口数量等,所以最好是通过多台PC机组成几个集群来对服务器进行压测. 本文目录: 1.软硬件配 ...

  2. python字符串与列表的相互转换

    学习内容: 1.字符串转列表 2.列表转字符串 1. 字符串转列表 s ='hello python !'li = s.split(' ') #注意:引号内有空格print (li)输出:['hell ...

  3. BZOJ4912 : [Sdoi2017]天才黑客

    建立新图,原图中每条边在新图中是点,点权为$w_i$,边权为两个字符串的LCP. 对字典树进行DFS,将每个点周围一圈边对应的字符串按DFS序从小到大排序. 根据后缀数组利用height数组求LCP的 ...

  4. keepalived+mysql backup服务器可ping通过vip但telnet vip+3306失败问题

    环境: OS:CentOS 7_X64 数据库:mysql-5.7 MASTER:192.168.119.23 BACKUP:192.168.119.24 VIP:192.168.119.138 ke ...

  5. 4989: [Usaco2017 Feb]Why Did the Cow Cross the Road

    题面:4989: [Usaco2017 Feb]Why Did the Cow Cross the Road 连接 http://www.lydsy.com/JudgeOnline/problem.p ...

  6. 12、Bootstrap中文文档(其它插件分享)

    给大家介绍一个前端框架让你从此写起前端代码与之先前相比如有神助般的效果拉就是Bootstrap. 本片导航: Bootstrap的下载 css样式的使用 JavaScript 效果的引用 其他前端插件 ...

  7. 从注册表清理 IE10,IE11 用户代理字符串(UserAgent)中的垃圾信息

    某一天,我发现我的 IE User Agent 字符串里面竟然含有刷机大师.百度浏览器等许多垃圾,国货流氓见怪不怪了. 微软自家的.NET CLR也占据了一大片,看着也不爽. 决定清理一下,但是却没找 ...

  8. RestTemplate之GET和POST调用和异步回调

    get方式 String url = "http://hostname:port/v1.0/data/data"; HttpHeaders headers = new HttpHe ...

  9. spring boot 中添加mongodb支持

    1.添加maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  10. windows下Graphviz安装及入门教程

    下载安装配置环境变量 intall 配置环境变量 验证 基本绘图入门 graph digraph 一个复杂的例子 和python交互 发现好的工具,如同发现新大陆.有时,我们会好奇,论文中.各种专业的 ...