java读写分离的实现
1.  背景
我们⼀般应⽤对⽽⾔都是“读多写少”,也就说对数据库读取数据的压⼒⽐较⼤,有⼀个思路就是说采⽤数据库集的⽅案,
其中⼀个是主库,负责写⼊数据,我们称之为:写库;
spring怎么读多个文件其它都是从库,负责读取数据,我们称之为:读库;
那么,对我们的要求是:
1、读库和写库的数据⼀致;(这个是很重要的⼀个问题,处理业务逻辑要放在service层去处理,不要在dao或者mapper层⾯去处理)
2、写数据必须写到写库;
3、读数据必须到读库;
2.  ⽅案
解决读写分离的⽅案有两种:应⽤层解决和中间件解决。
2.1. 应⽤层解决:
优点:
1、多数据源切换⽅便,由程序⾃动完成;
2、不需要引⼊中间件;
3、理论上⽀持任何数据库;
缺点:
1、由程序员完成,运维参与不到;
2、不能做到动态增加数据源;
2.2. 中间件解决
优缺点:
优点:
1、源程序不需要做任何改动就可以实现读写分离;
2、动态添加数据源不需要重启程序;
缺点:
1、程序依赖于中间件,会导致切换数据库变得困难;
2、由中间件做了中转代理,性能有所下降;
3.  使⽤Spring基于应⽤层实现
3.1. 原理
3.2. DynamicDataSource
/**
* 定义动态数据源,实现通过集成Spring提供的AbstractRoutingDataSource,只需要实现determineCurrentLookupKey⽅法即可 *
* 由于DynamicDataSource是单例的,线程不安全的,所以采⽤ThreadLocal保证线程安全,由DynamicDataSourceHolder完成。 *
* @author zhijun
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
// 使⽤DynamicDataSourceHolder保证线程安全,并且得到当前线程中的数据源key
DataSourceKey();
}
}
3.3. DynamicDataSourceHolder
<pre name="code" class="java">/**
*
* 使⽤ThreadLocal技术来记录当前线程中的数据源的key
*
* @author zhijun
*
*/
public class DynamicDataSourceHolder {
//写库对应的数据源key
private static final String MASTER = "master";
/
/读库对应的数据源key
private static final String SLAVE = "slave";
//使⽤ThreadLocal记录当前线程的数据源key
private static final ThreadLocal<String> holder = new ThreadLocal<String>();
/**
* 设置数据源key
* @param key
*/
public static void putDataSourceKey(String key) {
holder.set(key);
}
/
**
* 获取数据源key
* @return
*/
public static String getDataSourceKey() {
();
}
/**
* 标记写库
*/
public static void markMaster(){
putDataSourceKey(MASTER);
}
/**
* 标记读库
*/
public static void markSlave(){
putDataSourceKey(SLAVE);
}
}
3.4. DataSourceAspect
import org.apachemons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
/**
* 定义数据源的AOP切⾯,通过该Service的⽅法名判断是应该⾛读库还是写库
*
* @author zhijun
*
*/
public class DataSourceAspect {
/**
* 在进⼊Service⽅法之前执⾏
*
* @param point 切⾯对象
*/
public void before(JoinPoint point) {
// 获取到当前执⾏的⽅法名
String methodName = Signature().getName();
if (isSlave(methodName)) {
// 标记为读库
DynamicDataSourceHolder.markSlave();
} else {
// 标记为写库
DynamicDataSourceHolder.markMaster();
}
}
/**
* 判断是否为读库
*
* @param methodName
* @return
*/
private Boolean isSlave(String methodName) {
// ⽅法名以query、find、get开头的⽅法名⾛从库
return StringUtils.startsWithAny(methodName, "query", "find", "get");
}
}
3.5. 配置2个数据源
3.5.1.  jdbc.properties
jdbc.master.sql.jdbc.Driver
jdbc.master.url=jdbc:mysql://127.0.0.1:3306/mybatis_1128?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true jdbc.master.username=root
jdbc.master.password=123456
jdbc.slave01.sql.jdbc.Driver
jdbc.slave01.url=jdbc:mysql://127.0.0.1:3307/mybatis_1128?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true jdbc.slave01.username=root
jdbc.slave01.password=123456
3.5.2.  定义连接池
<!-- 配置连接池 -->
<bean id="masterDataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<!-- 数据库驱动 -->
<property name="driverClass" value="${jdbc.master.driver}" />
<!-- 相应驱动的jdbcUrl -->
<property name="jdbcUrl" value="${jdbc.master.url}" />
<!-- 数据库的⽤户名 -->
<property name="username" value="${jdbc.master.username}" />
<!-- 数据库的密码 -->
<property name="password" value="${jdbc.master.password}" />
<!-- 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 -->        <property name="idleConnectionTestPeriod" value="60" />
<!-- 连接池中未使⽤的链接最⼤存活时间,单位是分,默认值:60,如果要永远存活设置为0 -->
<property name="idleMaxAge" value="30" />
<!-- 每个分区最⼤的连接数 -->
<property name="maxConnectionsPerPartition" value="150" />
<!-- 每个分区最⼩的连接数 -->
<property name="minConnectionsPerPartition" value="5" />
</bean>
<!-- 配置连接池 -->
<bean id="slave01DataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<!-- 数据库驱动 -->
<property name="driverClass" value="${jdbc.slave01.driver}" />
<!-- 相应驱动的jdbcUrl -->
<property name="jdbcUrl" value="${jdbc.slave01.url}" />
<!-- 数据库的⽤户名 -->
<property name="username" value="${jdbc.slave01.username}" />
<!-- 数据库的密码 -->
<property name="password" value="${jdbc.slave01.password}" />
<!-- 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 -->        <property name="idleConnectionTestPeriod" value="60" />
<!-- 连接池中未使⽤的链接最⼤存活时间,单位是分,默认值:60,如果要永远存活设置为0 -->
<property name="idleMaxAge" value="30" />
<!-- 每个分区最⼤的连接数 -->
<property name="maxConnectionsPerPartition" value="150" />
<!-- 每个分区最⼩的连接数 -->
<property name="minConnectionsPerPartition" value="5" />
</bean>
3.5.3.  定义DataSource
<!-- 定义数据源,使⽤⾃⼰实现的数据源 -->
<bean id="dataSource" class="cn.itcast.usermanage.spring.DynamicDataSource">
<!-- 设置多个数据源 -->
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 这个key需要和程序中的key⼀致 -->
<entry key="master" value-ref="masterDataSource"/>
<entry key="slave" value-ref="slave01DataSource"/>
</map>
</property>
<!-- 设置默认的数据源,这⾥默认⾛写库 -->
<property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>
3.6. 配置事务管理以及动态切换数据源切⾯
3.6.1.  定义事务管理器
<!-- 定义事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
3.6.2.  定义事务策略
<!-- 定义事务策略 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--定义查询⽅法都是只读的 -->
<tx:method name="query*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<!-- 主库执⾏操作,事务传播⾏为定义为默认⾏为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<!--其他⽅法使⽤默认事务策略 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
3.6.3.  定义切⾯
<!-- 定义AOP切⾯处理器 -->
<bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect" />
<aop:config>
<!-- 定义切⾯,所有的service的所有⽅法 -->
<aop:pointcut id="txPointcut" expression="execution(* x.service.*.*(..))" />
<!-- 应⽤事务策略到Service切⾯ -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
<!-- 将切⾯应⽤到⾃定义的切⾯处理器上,-9999保证该切⾯优先级最⾼执⾏ -->
<aop:aspect ref="dataSourceAspect" order="-9999">
<aop:before method="before" pointcut-ref="txPointcut" />
</aop:aspect>
</aop:config>
4.  改进切⾯实现,使⽤事务策略规则匹配
之前的实现我们是将通过⽅法名匹配,⽽不是使⽤事务策略中的定义,我们使⽤事务管理策略中的规则匹配。
4.1. 改进后的配置
<bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect">
<!-- 指定事务策略 -->
<property name="txAdvice" ref="txAdvice"/>
<!-- 指定slave⽅法的前缀(⾮必须) -->
<property name="slaveMethodStart" value="query,find,get"/>
</bean>
4.2. 改进后的实现
import flect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apachemons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import ansaction.interceptor.NameMatchTransactionAttributeSource;
import ansaction.interceptor.TransactionAttribute;
import ansaction.interceptor.TransactionAttributeSource;
import ansaction.interceptor.TransactionInterceptor;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.ReflectionUtils;
/**
* 定义数据源的AOP切⾯,该类控制了使⽤Master还是Slave。
*

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。