spring+mybatis利用interceptor(plugin)兑现数据库读写分离

使用spring的动态路由实现数据库负载均衡

 

系统中存在的多台服务器是“地位相当”的,不过,同一时间他们都处于活动(Active)状态,处于负载均衡等因素考虑,数据访问请求需要在这几台数据库服务器之间进行合理分配, 这个时候,通过统一的一个DataSource来屏蔽这种请求分配的需求,从而屏蔽数据访问类与具体DataSource的耦合

系统中存在的多台数据库服务器现在地位可能相当也可能不相当,但数据访问类在系统启动时间无法明确到底应该使用哪一个数据源进行数据访问,而必须在系统运行期间通过某种条件来判定到底应该使用哪一个数据源,这个时候,我们也得使用这种“合纵连横”的方式向数据访问类暴露一个统一的DataSource,由该DataSource来解除数据访问类与具体数据源之间的过紧耦合;
更多场景需要读者根据具体的应用来判定,不过,并非所有的应用要做这样的处理,如果能够保持简单,那尽量保持简单.要实现这种“合纵连横”的多数据源管理方式,总的指导原则就是实现一个自定义的DataSource,让该DataSource来管理系统中存在的多个与具体数据库挂钩的数据源, 数据访问类只跟这个自定义的DataSource打交道即可。在spring2.0.1发布之前,各个项目中可能存在多种针对这种情况下的多数据源管理方式, 不过,spring2.0.1发布之后,引入了AbstractRoutingDataSource,使用该类可以实现普遍意义上的多数据源管理功能。

假设我们有三台数据库用来实现负载均衡,所有的数据访问请求最终需要平均的分配到这三台数据库服务器之上,那么,我们可以通过继承AbstractRoutingDataSource来快速实现一个满足这样场景的原型(Prototype):

public class PrototypeLoadBalanceDataSource extends AbstractRoutingDataSource  {  
     private Lock lock = new ReentrantLock();  
     private int counter = 0;  
    private int dataSourceNumber = 3;  
   @Override  
    protected Object determineCurrentLookupKey() {  
        lock.lock();  
        try{  
           counter++;  
            int lookupKey = counter % getDataSourceNumber();  
            return new Integer(lookupKey);  
        }finally{  
             lock.unlock();  
         }  
     }  
     // ...  
 
}

 

 

 

我们在介绍AbstractRoutingDataSource的时候说过,要继承该类,通常只需要给出determineCurrentLookupKey()方法的逻辑即可。 下面是针对PrototypeLoadBalanceDataSource的配置:

<bean id="dataSourc1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
02.    <property name="url" value=".."/>  
03.    <property name="driverClassName" value=".."/>  
04.    <property name="username" value=".."/>  
05.    <property name="password" value=".."/>  
06.    <!-- other property settings -->  
07.</bean>  
08.<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
09.    <property name="url" value=".."/>  
10.    <property name="driverClassName" value=".."/>  
11.    <property name="username" value=".."/>  
12.    <property name="password" value=".."/>  
13.    <!-- other property settings -->  
14.</bean>  
15.<bean id="dataSource3" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
16.    <property name="url" value=".."/>  
17.    <property name="driverClassName" value=".."/>  
18.    <property name="username" value=".."/>  
19.    <property name="password" value=".."/>  
20.    <!-- other property settings -->  
21.</bean>  
22.<util:map id="dataSources">  
23.    <entry key="0" value-ref="dataSource1"/>  
24.    <entry key="1" value-ref="dataSource2"/>  
25.    <entry key="2" value-ref="dataSource3"/>  
26.</util:map>  
27.<bean id="dataSourceLookup" class="org.springframework.jdbc.datasource.lookup.MapDataSourceLookup">  
28.    <constructor-arg>  
29.        <ref bean="dataSources"/>  
30.    </constructor-arg>  
31.</bean>  
32.<bean id="dataSource" class="..PrototypeLoadBalanceDataSource">  
33.    <property name="defaultTargetDataSource" ref="dataSourc1"/>  
34.    <property name="targetDataSources" ref="dataSources"/>  
35.    <property name="dataSourceLookup" ref=""/>  
36.</bean>  
37.<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
38.    <property name="dataSource" ref="dataSource"/>  
39.</bean>  
40.<bean id="someDao" class="...">  
41.    <property name=""jdbcTemplate"" ref=""jdbcTemplate""/>  
42.    <!-- other property settings -->  
43.</bean>  

 使用spring的动态路由实现数据库读写分离

Spring2.0.1以后的版本已经支持配置多数据源,并且可以在运行的时候动态加载不同的数据源。通过继承AbstractRoutingDataSource就可以实现多数据源的动态转换。目前做的项目就是需要访问2个数据源,每个数据源的表结构都是相同的,所以要求数据源的变动对于编码人员来说是透明,也就是说同样SQL语句在不同的环境下操作的数据库是不一样的。具体的流程如下:

 

1.建立一个获得和设置上下文的类

package com.lvye.base.dao.impl.jdbc;  
02./** 
03. *连接哪个数据源的环境变量 
04. */  
05.public class JdbcContextHolder {  
06.    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();    
07.    public static void setJdbcType(String jdbcType) {    
08.        contextHolder.set(jdbcType);  
09.    }    
10.    public static void setSlave(){  
11.        setJdbcType("slave");  
12.    }  
13.    public static void setMaster(){  
14.        clearJdbcType();  
15.    }  
16.    public static String getJdbcType(){    
17.        return (String) contextHolder.get();   
18.    }    
19.    public static void clearJdbcType() {    
20.        contextHolder.remove();    
21.    }    
22.}  

 2.建立动态数据源类,这个类必须继承AbstractRoutingDataSource

package com.lvye.base.dao.impl.jdbc;  
02.import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;    
03.public class DynamicDataSource extends AbstractRoutingDataSource{  
04.    /*(non-Javadoc) 
05.     *@see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() 
06.     *@author wenc 
07.     */  
08.     @Override  
09.     protected Object determineCurrentLookupKey() {  
10.        return JdbcContextHolder.getJdbcType();  
11.     }  
12.}  

 这个类实现了determineCurrentLookupKey方法,该方法返回一个Object,一般是返回字符串。该方法中直接使用了JdbcContextHolder.getJdbcType();方法获得上下文环境并直接返回。

 

 

3.编写spring的配置文件配置数据源

<beans>  
02.    <bean id="master" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
03.        <property name="driverClass">  
04.            <value>com.mysql.jdbc.Driver</value>  
05.        </property>  
06.        <property name="jdbcUrl">  
07.            <value>jdbc:mysql://192.168.18.143:3306/wenhq?useUnicode=true&characterEncoding=utf-8</value>  
08.        </property>  
09.        <property name="user">  
10.            <value>root</value>  
11.        </property>  
12.        <property name="password">  
13.            <value></value>  
14.        </property>  
15.    </bean>  
16.    <bean id="slave" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
17.        <property name="driverClass">  
18.            <value>com.mysql.jdbc.Driver</value>  
19.        </property>  
20.        <property name="jdbcUrl">  
21.            <value>jdbc:mysql://192.168.18.144:3306/ wenhq?useUnicode=true&characterEncoding=utf-8</value>  
22.        </property>  
23.        <property name="user">  
24.            <value>root</value>  
25.        </property>  
26.        <property name="password">  
27.            <value></value>  
28.        </property>  
29.    </bean>  
30.    <bean id="mySqlDataSource" class="com.lvye.base.dao.impl.jdbc.DynamicDataSource">   
31.        <property name="targetDataSources">   
32.            <map>   
33.                <entry key="slave" value-ref="slave"/>   
34.            </map>   
35.        </property>   
36.        <property name="defaultTargetDataSource" ref="master"/>   
37.    </bean>   
38.    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
39.        <property name="dataSource" ref="mySqlDataSource" />  
40.    </bean>  
41.    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
42.        <property name="dataSource" ref="mySqlDataSource" />  
43.    </bean>  
44.</beans>  

 在这个配置中可以看到首先配置两个真实的数据库连接,使用的msyql数据库;master和slave是按照mysql配置的主从关系的数据库,数据会自动实时同步mySqlDataSource会根据上下文选择不同的数据源。在这个配置中第一个property属性配置目标数据源,<entry key="slave" value-ref=" slave"/>中key的值必须要和JdbcContextHolder类中设置的参数值相同,如果有多个值,可以配置多个<entry>标签。第二个property属性配置默认的数据源,我们一般默认为主数据库。有些朋友喜欢使用hibernate,只需要把上面的jdbcTemplate替换为hibernate的就可以了。

4.多数据库连接配置完毕,简单测试

public void testSave() throws Exception{    
02.    jdbcContextHolder.setSlave();//设置从数据源    
03.    Test test = new Test();    
04.    test.setTest("www.wenhq.com.cn");               
05.    mydao.save(test);//使用dao保存实体             
06.     jdbcContextHolder.setMaster();//设置主数据源  
07.    mydao.save(test);//使用dao保存实体到另一个库中             
08.}    

 5.实现读写分离,上面的测试通过了,现在就简单了我的程序是使用jdbc实现的保存数据,只是使用了c3p0的数据库连接池而已。把所有访问数据库的方法包装一下,统一调用。把执行更新的sql发送到主数据库了

public void execute(String sql) {  
02.    JdbcContextHolder.setMaster();  
03.    log.debug("execute-sql:" + sql);  
04.    jdbcTemplate.execute(sql);  
05.}      

 把查询的发送到从数据库,需要注意的是像LAST_INSERT_ID这类的查询需要特殊处理,必须发送到主数据库,建议增加专门的方法,用于获取自增长的主键。

public List findObject(String queryString, Class clazz) {  
02.    JdbcContextHolder.setSlave();  
03.    log.debug("findObject-sql:" + queryString);  
04.    List list = jdbcTemplate.queryForList(queryString);  
05.    try {  
06.        list = StringBase.convertList(list, clazz);// 将List转化为List<clazz>  
07.    } catch (Exception e) {  
08.        log.error("List convert List<Object> error:" + e);  
09.    }  
10.    AbstractRoutingDataSourcereturn list;  
11.}  

 

 

spring+mybatis利用interceptor(plugin)实现数据库读写分离

 

1. 前提

    好长时间不写博客了,应该吐槽,写点什么东西了!最近在研究数据库读写分离,分表分库的一些东西。其实这个问题好早之前就想好,只是以前使用hibernate,难点是不好判断什么样的sql走读库,什么样的sql走主库?用正则匹配开头或许可以,/^select 没想出什么好的解决方法,mybatis就不一样了,mappedstatement有commandtype属性,象select,update,delete等类型,为实现读写分离打下来良好的基础。

2. 解决方法

    LazyConnectionProxy + RoutingDataSource +   Plugin

在SqlSessionTemplate,创建DefaultSqlSession的时候,使用connection proxy的代理,这时并没有真正的获取connection,因为我们不知道是要取读还是写的数据源。待到StatementHandler的prepare()使用connection创建PreparedStatement的时候再根据mappedstatement的commandType去路由获取真实的connection。

   RoutingDataSource支持一主一从,或者一主多从并采用round robin的方式简单负载均衡,预留接口路由和负载均衡策略可自定义。

   不支持事务,适合auto commit为true的场景。表述能力

01.<?xml version="1.0" encoding="UTF-8"?>  
02.<beans xmlns="http://www.springframework.org/schema/beans"  
03.        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
04.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
05.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
06.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
07.        http://www.springframework.org/schema/aop   
08.        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
09.        http://www.springframework.org/schema/tx    
10.        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
11.        http://www.springframework.org/schema/context  
12.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
13.  
14.        <!-- 导入属性配置文件 -->  
15.        <context:property-placeholder location="classpath*:*.properties" />  
16.  
17.    <bean id="abstractDataSource" abstract="true"  
18.                class="com.mchange.v2.c3p0.ComboPooledDataSource"  
19.                destroy-method="close">  
20.                <property name="driverClass" value="com.mysql.jdbc.Driver" />  
21.                <property name="user" value="root" />  
22.                <property name="password" value="" />  
23.        </bean>  
24.  
25.        <bean id="readDS" parent="abstractDataSource">  
26.                <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />  
27.        </bean>  
28.          
29.        <bean id="writeDS" parent="abstractDataSource">  
30.                <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />  
31.        </bean>  
32.          
33.        <!--简单的一个master和一个slaver 读写分离的数据源 -->  
34.        <bean id="routingDS" class="com.test.rwmybatis.RoutingDataSource">  
35.            <property name="targetDataSources">  
36.                 <map key-type="java.lang.String">  
37.                     <entry key="read" value-ref="readDS"></entry>  
38.                     <entry key="write" value-ref="writeDS"></entry>  
39.                 </map>  
40.            </property>  
41.            <property name="defaultTargetDataSource" ref="writeDS"></property>  
42.        </bean>  
43.          
44.        <!-- 适用于一个master和多个slaver的场景,并用roundrobin做负载均衡 -->  
45.        <bean id="roundRobinDs"  class="com.test.rwmybatis.RoundRobinRWRoutingDataSource">  
46.              <property name="writeDataSource"  ref="writeDS"></property>  
47.              <property name="readDataSoures">  
48.                  <list>  
49.                      <ref bean="readDS"/>  
50.                      <ref bean="readDS"/>  
51.                      <ref bean="readDS"/>  
52.                  </list>  
53.              </property>  
54.              <property name="readKey" value="READ"></property>  
55.              <property name="writeKey" value="WRITE"></property>  
56.        </bean>  
57.          
58.        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
59.                <property name="dataSource" ref="routingDS" />  
60.                <property name="configLocation" value="classpath:mybatis-config.xml" />  
61.                <!-- mapper和resultmap配置路径 -->  
62.                <property name="mapperLocations">  
63.                        <list>  
64.                                <value>classpath:com/test/rwmybatis/mapper/**/*-Mapper.xml  
65.                                </value>  
66.                        </list>  
67.                </property>  
68.        </bean>  
69.          
70.        <bean id="sqlSessionTemplate" class="com.test.rwmybatis.RWSqlSessionTemplate">   
71.      <constructor-arg ref="sqlSessionFactory" />  
72.    </bean>  
73.        <!-- 通过扫描的模式,扫描目录下所有的mapper, 根据对应的mapper.xml为其生成代理类-->  
74.        <bean id="mapper" class="com.test.rwmybatis.RWMapperScannerConfigurer">  
75.                <property name="basePackage" value="com.test.rwmybatis.mapper" />  
76.                <property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property>  
77.        </bean>  
78.  
79.<!--    <bean id="monitor" class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor"></bean> -->  
80.<!--    <aop:config> -->  
81.<!--       <aop:pointcut expression="execution(* com.taofang.smc.persistence..*.*(..))"  id="my_pc"/> -->  
82.<!--       <aop:advisor advice-ref="monitor" pointcut-ref="my_pc"/> -->  
83.<!--    </aop:config> -->  
84.</beans>  



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值