前提:已成功搭建mysql主从集群。
mysql主从复制环境搭建
原理:首先使用spring配置动态数据源,然后使用切面拦截service方法,判断执行的是写操作还是读操作,以此来动态的修改此次请求所使用的数据源。
源码:https://github.com/li5454yong/springdatesource.git
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<description>Spring公共配置</description>
<context:component-scan base-package="com.lxg.*" />
<!-- 配置主数据源 -->
<bean id="dataSourceMaster" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.master.url}" />
<property name="username" value="${jdbc.master.username}" />
<property name="password" value="${jdbc.master.password}" />
</bean>
<!-- 配置从数据源 -->
<bean id="dataSourceSlaver" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.slaver.url}" />
<property name="username" value="${jdbc.slaver.username}" />
<property name="password" value="${jdbc.slaver.password}" />
</bean>
<bean id="dataSource" class="com.lxg.springdatesource.DynamicDataSource">
<!-- 通过key-value的形式来关联数据源 -->
<property name="targetDataSources">
<map>
<entry value-ref="dataSourceMaster" key="Master"></entry>
<entry value-ref="dataSourceSlaver" key="Slaver"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceMaster" />
</bean>
<!-- MyBatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 显式指定Mapper文件位置 -->
<property name="mapperLocations" value="classpath*:/mybatis/*Mapper.xml" />
<!-- mybatis配置文件路径 -->
<property name="configLocation" value="classpath:/mybatis/config.xml" />
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<!-- 这个执行器会批量执行更新语句, 还有SIMPLE 和 REUSE -->
<constructor-arg index="1" value="BATCH" />
</bean>
<!-- 扫描basePackage接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 映射器接口文件的包路径, -->
<property name="basePackage" value="com.lxg.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 开启注解式事务控制 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义事务策略 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"/>
<!-- 定义AOP切面处理器 -->
<bean class="com.lxg.springdatesource.DataSourceAspect" id="dataSourceAspect" />
<aop:config>
<!--pointcut元素定义一个切入点,execution中的第一个星号 用以匹配方法的返回类型, 这里星号表明匹配所有返回类型。
com.lxg.service.*.*(..)表明匹配com.lxg.service包下的所有类的所有
方法 -->
<aop:pointcut id="myPointcut" expression="execution(* com.lxg.service.impl.*.*(..))" />
<!--将定义好的事务处理策略应用到上述的切入点 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
<!-- 将切面应用到自定义的切面处理器上,-9999保证该切面优先级最高执行 -->
<aop:aspect ref="dataSourceAspect" order="-9999">
<aop:before method="before" pointcut-ref="myPointcut" />
</aop:aspect>
</aop:config>
<!-- production环境 -->
<beans>
<context:property-placeholder
ignore-unresolvable="true" file-encoding="utf-8" location="classpath:jdbc.properties" />
</beans>
</beans>
数据库连接信息:
jdbc.driver=com.mysql.jdbc.Driver
#主数据库
jdbc.master.url=jdbc:mysql://localhost:3306/slave_lxg
jdbc.master.username=root
jdbc.master.password=root
#从数据库
jdbc.slaver.url=jdbc:mysql://192.168.0.12:3306/slave_lxg
jdbc.slaver.username=root
jdbc.slaver.password=root
aop切面:
DataSourceAspect.java
package com.lxg.springdatesource;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
/**
* 定义数据源的AOP切面,通过该Service的方法名判断是应该走读库还是写库
*
*/
public class DataSourceAspect {
/**
* 在进入Service方法之前执行
*
* @param point 切面对象
*/
public void before(JoinPoint point) {
// 获取到当前执行的方法名
String methodName = point.getSignature().getName();
if (isSlave(methodName)) {
// 标记为从库
DBContextHolder.setDBType(DBContextHolder.DATA_SOURCE_SLAVER);
} else {
// 标记为主库
DBContextHolder.setDBType(DBContextHolder.DATA_SOURCE_MASTER);
}
}
/**
* 判断是否为读库
*
* @param methodName
* @return
*/
private Boolean isSlave(String methodName) {
// 方法名以query、find、get开头的方法名走从库
return StringUtils.startsWithAny(methodName, "query", "find", "get");
}
}
DBContextHolder.java
package com.lxg.springdatesource;
public class DBContextHolder{
public static final String DATA_SOURCE_MASTER = "Master";
public static final String DATA_SOURCE_SLAVER = "Slaver";
private static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<String>();
public static void setDBType(String dbType) {
THREAD_LOCAL.set(dbType);
}
public static String getDBType() {
return THREAD_LOCAL.get();
}
public static void clearDBType() {
THREAD_LOCAL.remove();
}
}
DynamicDataSource.java
package com.lxg.springdatesource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DBContextHolder.getDBType();
}
}
原文:https://blog.csdn.net/u283056051/article/details/52564304