大部分应用都是读多写少,也就说对数据库读取数据的压力比较大。我们可以采用读写分离的模式减少数据库读的压力。基于应用层的读写分离方案,多数据源切换方便,由程序自动完成。下面是基于应用的读写分离方案的模式:
![](https://img.haomeiwen.com/i5543739/242cf2f1a3f7ca35.png)
解决方案
一、原理
![](https://img.haomeiwen.com/i5543739/8b63813acbed03fa.png)
在进入service之前,使用AOP来作出判断,是使用写库还是使用读库,判断依据可以根据方法名进行判断,比如说以query、find、get等开头的就走读库,其他的走写库。
二、具体代码实现
1、DynamicDataSource
由于DynamicDataSource是单例的,线程不安全的,所以采用ThreadLocal来保证线程安全,由DynamicDataSourceHolder完成。
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
//使用DynamicDataSourceHolder保证线程安全,并且得到当前线程中的数据源key
return DynamicDataSourceHolder.getDataSourceKey();
}
}
2、DynamicDataSourceHolder
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>();
//设置数据源
public static void putDataSourceKey(String key) {
holder.set(key);
}
//获取数据源
public static String getDataSourceKey() {
return holder.get();
}
//标记写数据库
public static void markMaster(){
putDataSourceKey(MASTER);
}
//标记读数据库
public static void markSlave(){
putDataSourceKey(SLAVE);
}
}
3、DataSourceAspect
定义数据源的AOP切面,通过该Service的方法名判断是应该走读库还是写库
public class DataSourceAspect{
//在进入Service方法之前执行
public void before(JoinPoint point) {
// 获取到当前执行的方法名
String methodName = point.getSignature().getName();
if (isSlave(methodName)) {
// 标记为读库
DynamicDataSourceHolder.markSlave();
}else{
// 标记为写库
DynamicDataSourceHolder.markMaster();
}
}
//判断是否走读库
private Boolean isSlave(String methodName) {
// 方法名以query、find、get开头的方法名走从库 }
return StringUtils.startsWithAny(methodName, "query", "find", "get");
}
}
4、配置2个数据源
jdbc.master.driver=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://127.0.0.1:3306/mybatis_1128useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.master.username=root
jdbc.master.password=123456
jdbc.slave01.driver=com.mysql.jdbc.Driver
jdbc.slave01.url=jdbc:mysql://127.0.0.1:3307/mybatis_1128useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.slave01.username=root
jdbc.slave01.password=123456
5、定义连接池
<!-- 配置连接池 -->
<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>
6、定义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>
7、定义事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
8、定义事务策略
<!-- 定义事务策略 -->
<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>
9、定义切面
<!-- 定义AOP切面处理器 -->
<bean class="cn.itcast.usermanage.spring.DataSourceAspect"id="dataSourceAspect" />
<aop:config>
<!-- 定义切面,所有的service的所有方法 -->
<aop:pointcut id="txPointcut" expression="execution(* xx.xxx.xxxxxxx.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>
至此,简单的基于应用层的读写分离就实现了。
网友评论