使用Spring实现读写分离( MySQL实现主从复制)
时间:2021-07-01 10:21:17
帮助过:21人阅读
- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
-
- public class DynamicDataSource extends AbstractRoutingDataSource{
-
- @Override
- protected Object determineCurrentLookupKey() {
-
- return DynamicDataSourceHolder.getDataSourceKey();
- }
-
- }
3.3. DynamicDataSourceHolder
[java] view plain
copy
- <pre name="code" class="java">
- public class DynamicDataSourceHolder {
-
-
- private static final String MASTER = "master";
-
-
- private static final String SLAVE = "slave";
-
-
- 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.4. DataSourceAspect
[java] view plain
copy
- import org.apache.commons.lang3.StringUtils;
- import org.aspectj.lang.JoinPoint;
-
- public class DataSourceAspect {
-
-
- public void before(JoinPoint point) {
-
- String methodName = point.getSignature().getName();
- if (isSlave(methodName)) {
-
- DynamicDataSourceHolder.markSlave();
- } else {
-
- DynamicDataSourceHolder.markMaster();
- }
- }
-
-
- private Boolean isSlave(String methodName) {
-
- return StringUtils.startsWithAny(methodName, "query", "find", "get");
- }
-
- }
3.5. 配置2个数据源
3.5.1. jdbc.properties
[java] view plain
copy
- jdbc.master.driver=com.mysql.jdbc.Driver
- jdbc.master.url=jdbc:mysql:
- jdbc.master.username=root
- jdbc.master.password=123456
-
-
- jdbc.slave01.driver=com.mysql.jdbc.Driver
- jdbc.slave01.url=jdbc:mysql:
- jdbc.slave01.username=root
- jdbc.slave01.password=123456
3.5.2. 定义连接池
[html] view plain
copy
- <bean id="masterDataSource" class="com.jolbox.bonecp.BoneCPDataSource"
- destroy-method="close">
-
- <property name="driverClass" value="${jdbc.master.driver}" />
-
- <property name="jdbcUrl" value="${jdbc.master.url}" />
-
- <property name="username" value="${jdbc.master.username}" />
-
- <property name="password" value="${jdbc.master.password}" />
-
- <property name="idleConnectionTestPeriod" value="60" />
-
- <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}" />
-
- <property name="jdbcUrl" value="${jdbc.slave01.url}" />
-
- <property name="username" value="${jdbc.slave01.username}" />
-
- <property name="password" value="${jdbc.slave01.password}" />
-
- <property name="idleConnectionTestPeriod" value="60" />
-
- <property name="idleMaxAge" value="30" />
-
- <property name="maxConnectionsPerPartition" value="150" />
-
- <property name="minConnectionsPerPartition" value="5" />
- </bean>
3.5.3. 定义DataSource
[html] view plain
copy
- <bean id="dataSource" class="cn.itcast.usermanage.spring.DynamicDataSource">
-
- <property name="targetDataSources">
- <map key-type="java.lang.String">
-
- <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. 定义事务管理器
[html] view plain
copy
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
3.6.2. 定义事务策略
[html] view plain
copy
- <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. 定义切面
[html] view plain
copy
- <bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect" />
-
- <aop:config>
-
- <aop:pointcut id="txPointcut" expression="execution(* xx.xxx.xxxxxxx.service.*.*(..))" />
-
- <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
-
-
- <aop:aspect ref="dataSourceAspect" order="-9999">
- <aop:before method="before" pointcut-ref="txPointcut" />
- </aop:aspect>
- </aop:config>
4. 改进切面实现,使用事务策略规则匹配
之前的实现我们是将通过方法名匹配,而不是使用事务策略中的定义,我们使用事务管理策略中的规则匹配。
4.1. 改进后的配置
[html] view plain
copy
- <span style="white-space:pre"> </span>
- <bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect">
-
- <property name="txAdvice" ref="txAdvice"/>
-
- <property name="slaveMethodStart" value="query,find,get"/>
- </bean>
4.2. 改进后的实现
[java] view plain
copy
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.commons.lang3.StringUtils;
- import org.aspectj.lang.JoinPoint;
- import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
- import org.springframework.transaction.interceptor.TransactionAttribute;
- import org.springframework.transaction.interceptor.TransactionAttributeSource;
- import org.springframework.transaction.interceptor.TransactionInterceptor;
- import org.springframework.util.PatternMatchUtils;
- import org.springframework.util.ReflectionUtils;
-
- public class DataSourceAspect {
-
- private List<String> slaveMethodPattern = new ArrayList<String>();
-
- private static final String[] defaultSlaveMethodStart = new String[]{ "query", "find", "get" };
-
- private String[] slaveMethodStart;
-
-
- @SuppressWarnings("unchecked")
- public void setTxAdvice(TransactionInterceptor txAdvice) throws Exception {
- if (txAdvice == null) {
-
- return;
- }
-
- TransactionAttributeSource transactionAttributeSource = txAdvice.getTransactionAttributeSource();
- if (!(transactionAttributeSource instanceof NameMatchTransactionAttributeSource)) {
- return;
- }
-
- NameMatchTransactionAttributeSource matchTransactionAttributeSource = (NameMatchTransactionAttributeSource) transactionAttributeSource;
- Field nameMapField = ReflectionUtils.findField(NameMatchTransactionAttributeSource.class, "nameMap");
- nameMapField.setAccessible(true);
-
- Map<String, TransactionAttribute> map = (Map<String, TransactionAttribute>) nameMapField.get(matchTransactionAttributeSource);
-
-
- for (Map.Entry<String, TransactionAttribute> entry : map.entrySet()) {
- if (!entry.getValue().isReadOnly()) {
- continue;
- }
- slaveMethodPattern.add(entry.getKey());
- }
- }
-
-
- public void before(JoinPoint point) {
-
- String methodName = point.getSignature().getName();
-
- boolean isSlave = false;
-
- if (slaveMethodPattern.isEmpty()) {
-
- isSlave = isSlave(methodName);
- } else {
-
- for (String mappedName : slaveMethodPattern) {
- if (isMatch(methodName, mappedName)) {
- isSlave = true;
- break;
- }
- }
- }
-
- if (isSlave) {
-
- DynamicDataSourceHolder.markSlave();
- } else {
-
- DynamicDataSourceHolder.markMaster();
- }
- }
-
-
- private Boolean isSlave(String methodName) {
-
- return StringUtils.startsWithAny(methodName, getSlaveMethodStart());
- }
-
-
- protected boolean isMatch(String methodName, String mappedName) {
- return PatternMatchUtils.simpleMatch(mappedName, methodName);
- }
-
-
- public void setSlaveMethodStart(String[] slaveMethodStart) {
- this.slaveMethodStart = slaveMethodStart;
- }
-
- public String[] getSlaveMethodStart() {
- if(this.slaveMethodStart == null){
-
- return defaultSlaveMethodStart;
- }
- return slaveMethodStart;
- }
-
- }
5. 一主多从的实现
很多实际使用场景下都是采用“一主多从”的架构的,所有我们现在对这种架构做支持,目前只需要修改DynamicDataSource即可。
5.1. 实现
[java] view plain
copy
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.concurrent.atomic.AtomicInteger;
-
- import javax.sql.DataSource;
-
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
- import org.springframework.util.ReflectionUtils;
-
- public class DynamicDataSource extends AbstractRoutingDataSource {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);
-
- private Integer slaveCount;
-
-
- private AtomicInteger counter = new AtomicInteger(-1);
-
-
- private List<Object> slaveDataSources = new ArrayList<Object>(0);
-
- @Override
- protected Object determineCurrentLookupKey() {
-
- if (DynamicDataSourceHolder.isMaster()) {
- Object key = DynamicDataSourceHolder.getDataSourceKey();
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("当前DataSource的key为: " + key);
- }
- return key;
- }
- Object key = getSlaveKey();
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("当前DataSource的key为: " + key);
- }
- return key;
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void afterPropertiesSet() {
- super.afterPropertiesSet();
-
-
- Field field = ReflectionUtils.findField(AbstractRoutingDataSource.class, "resolvedDataSources");
- field.setAccessible(true);
-
- try {
- Map<Object, DataSource> resolvedDataSources = (Map<Object, DataSource>) field.get(this);
-
- this.slaveCount = resolvedDataSources.size() - 1;
- for (Map.Entry<Object, DataSource> entry : resolvedDataSources.entrySet()) {
- if (DynamicDataSourceHolder.MASTER.equals(entry.getKey())) {
- continue;
- }
- slaveDataSources.add(entry.getKe