前言
接着上一篇文章Spring事务基础,本文主要是关于Spring多数据源的情况下如何保证事务正常回滚。这里也是使用大家广泛使用的jta-atomikos进行,我只是做一些总结方便以后自己直接拿来用。
如果你非常着急,那么可以直接下载这个项目看看即可:
https://github.com/xbmchina/multidatatsource-druid/tree/master/multidatasource-atomikos
总体思路
网上已经有很多关于jta-atomikos的相关文章,本文可能有点绕,不容易看得懂,所以在此描述一下思路:
1、配置mybatis以及druid使得其能够实现连接多个数据源。
2、通过自定义数据源,将多个数据源的事务整合成一个SqlSession,进而实现统一管理事务。
3、利用AOP以及自定义注解实现动态的切换数据源(即是A的dao应该连接A的数据源。)。
更多详细了解可以查看源码,或者下面的简单介绍。
添加依赖
主要依赖就是jta-atomikos,其余的mybatis与druid的相关依赖就不粘贴了。
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-aop</artifactId>
-
</dependency>
-
<!--atomikos transaction management-->
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
-
</dependency>
配置多个数据源
1、首先,定义一个枚举来说明一下当前数据源实例key有哪些。
-
publicclassDataSourceKey{
-
/** 数据库源one*/
-
publicstaticfinalString ONE= "one";
-
-
/** 数据库源two*/
-
publicstaticfinalString TWO= "two";
-
}
2、其次,使用ThreadLocal存储当前使用数据源实例的key。ThreadLocal实例化的时候给一个master的默认值,也就是默认数据源是master数据源。
-
publicclassDynamicDataSourceContextHolder{
-
-
privatestaticThreadLocal<Object> CONTEXT_HOLDER = ThreadLocal.withInitial(() -> DataSourceKey.MASTER.getName());
-
-
publicstaticList<Object> dataSourceKeys = newArrayList<Object>();
-
-
publicstaticvoid setDataSourceKey(String key){
-
CONTEXT_HOLDER.set(key);
-
}
-
-
publicstaticObject getDataSourceKey(){
-
return CONTEXT_HOLDER.get();
-
}
-
-
publicstaticvoid clearDataSourceKey(){
-
CONTEXT_HOLDER.remove();
-
}
-
-
publicstaticBoolean containDataSourceKey(String key){
-
return dataSourceKeys.contains(key);
-
}
-
-
}
3、重写AbstractRoutingDataSource的determineCurrentLookupKey方法,在访问数据库时会调用该类的 determineCurrentLookupKey() 方法获取数据库实例的 key。
-
publicclassDynamicDataSourceextendsAbstractRoutingDataSource{
-
-
/**
-
* 取得当前使用那个数据源。
-
*/
-
@Override
-
protectedObject determineCurrentLookupKey() {
-
returnDataSourceContextHolder.getDatasourceType();
-
}
-
-
}
4、通过SqlSessionFactory 重新组装整合多个数据源,最终返回sqlSessionTemplate给到dao层。
-
@Configuration
-
@MapperScan(basePackages = MyBatisConfig.BASE_PACKAGE, sqlSessionTemplateRef = "sqlSessionTemplate")
-
publicclassMyBatisConfigextendsAbstractDataSourceConfig{
-
-
//mapper模式下的接口层
-
staticfinalString BASE_PACKAGE = "cn.xbmchina.multidatasourceatomikos.mapper";
-
-
//对接数据库的实体层
-
staticfinalString ALIASES_PACKAGE = "ccn.xbmchina.multidatasourceatomikos.domain";
-
-
staticfinalString MAPPER_LOCATION = "classpath:mapper/*.xml";
-
-
-
@Primary
-
@Bean(name = "dataSourceOne")
-
publicDataSource dataSourceOne(Environment env) {
-
String prefix = "spring.datasource.druid.one.";
-
return getDataSource(env,prefix,"one");
-
}
-
-
@Bean(name = "dataSourceTwo")
-
publicDataSource dataSourceTwo(Environment env) {
-
String prefix = "spring.datasource.druid.two.";
-
return getDataSource(env,prefix,"two");
-
}
-
-
-
-
@Bean("dynamicDataSource")
-
publicDynamicDataSource dynamicDataSource(@Qualifier("dataSourceOne")DataSource dataSourceOne, @Qualifier("dataSourceTwo")DataSource dataSourceTwo) {
-
Map<Object, Object> targetDataSources = newHashMap<>();
-
targetDataSources.put("one",dataSourceOne);
-
targetDataSources.put("two",dataSourceTwo);
-
-
DynamicDataSource dataSource = newDynamicDataSource();
-
dataSource.setTargetDataSources(targetDataSources);
-
dataSource.setDefaultTargetDataSource(dataSourceOne);
-
return dataSource;
-
}
-
-
@Bean(name = "sqlSessionFactoryOne")
-
publicSqlSessionFactory sqlSessionFactoryOne(@Qualifier("dataSourceOne") DataSource dataSource)
-
throwsException{
-
return createSqlSessionFactory(dataSource);
-
}
-
-
@Bean(name = "sqlSessionFactoryTwo")
-
publicSqlSessionFactory sqlSessionFactoryTwo(@Qualifier("dataSourceTwo") DataSource dataSource)
-
throwsException{
-
return createSqlSessionFactory(dataSource);
-
}
-
-
-
-
-
@Bean(name = "sqlSessionTemplate")
-
publicCustomSqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactoryOne")SqlSessionFactory factoryOne, @Qualifier("sqlSessionFactoryTwo")SqlSessionFactory factoryTwo) throwsException{
-
Map<Object,SqlSessionFactory> sqlSessionFactoryMap = newHashMap<>();
-
sqlSessionFactoryMap.put("one",factoryOne);
-
sqlSessionFactoryMap.put("two",factoryTwo);
-
-
CustomSqlSessionTemplate customSqlSessionTemplate = newCustomSqlSessionTemplate(factoryOne);
-
customSqlSessionTemplate.setTargetSqlSessionFactorys(sqlSessionFactoryMap);
-
return customSqlSessionTemplate;
-
}
-
-
/**
-
* 创建数据源
-
* @param dataSource
-
* @return
-
*/
-
privateSqlSessionFactory createSqlSessionFactory(DataSource dataSource) throwsException{
-
SqlSessionFactoryBean bean = newSqlSessionFactoryBean();
-
bean.setDataSource(dataSource);
-
bean.setVfs(SpringBootVFS.class);
-
bean.setTypeAliasesPackage(ALIASES_PACKAGE);
-
bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
-
return bean.getObject();
-
}
-
}
5、使用AOP,以自定义注解注解在的方法为切点,动态切换数据源
-
import cn.xbmchina.multidatasourceatomikos.annotations.TargetDataSource;
-
import cn.xbmchina.multidatasourceatomikos.db.DataSourceContextHolder;
-
import org.aspectj.lang.JoinPoint;
-
import org.aspectj.lang.annotation.After;
-
import org.aspectj.lang.annotation.Before;
-
import org.aspectj.lang.annotation.Pointcut;
-
-
import java.lang.reflect.Method;
-
-
publicclassDataSourceAspect{
-
protectedstaticfinalThreadLocal<String> preDatasourceHolder = newThreadLocal<>();
-
-
/**
-
* @param clazz
-
* @param name
-
* @return
-
*/
-
privatestaticMethod findUniqueMethod(Class<?> clazz, String name) {
-
Class<?> searchType = clazz;
-
while(searchType != null) {
-
Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods());
-
for(Method method : methods) {
-
if(name.equals(method.getName())) {
-
return method;
-
}
-
}
-
searchType = searchType.getSuperclass();
-
}
-
returnnull;
-
}
-
-
@Pointcut("@annotation(cn.xbmchina.multidatasourceatomikos.annotations.TargetDataSource)")
-
protectedvoid datasourceAspect() {
-
-
}
-
-
/**
-
* 根据@TargetDataSource的属性值设置不同的dataSourceKey,以供DynamicDataSource
-
*/
-
@Before("datasourceAspect()")
-
publicvoid changeDataSourceBeforeMethodExecution(JoinPoint jp) {
-
String key = determineDatasource(jp);
-
if(key == null) {
-
DataSourceContextHolder.setDatasourceType(null);
-
return;
-
}
-
preDatasourceHolder.set(DataSourceContextHolder.getDatasourceType());
-
DataSourceContextHolder.setDatasourceType(key);
-
-
}
-
-
/**
-
* @param jp
-
* @return
-
*/
-
publicString determineDatasource(JoinPoint jp) {
-
String methodName = jp.getSignature().getName();
-
Class targetClass = jp.getSignature().getDeclaringType();
-
String dataSourceForTargetClass = resolveDataSourceFromClass(targetClass);
-
String dataSourceForTargetMethod = resolveDataSourceFromMethod(targetClass, methodName);
-
String resultDS = determinateDataSource(dataSourceForTargetClass, dataSourceForTargetMethod);
-
return resultDS;
-
}
-
-
/**
-
*
-
*/
-
@After("datasourceAspect()")
-
publicvoid restoreDataSourceAfterMethodExecution() {
-
DataSourceContextHolder.setDatasourceType(preDatasourceHolder.get());
-
preDatasourceHolder.remove();
-
}
-
-
/**
-
* @param targetClass
-
* @param methodName
-
* @return
-
*/
-
privateString resolveDataSourceFromMethod(Class targetClass, String methodName) {
-
Method m = findUniqueMethod(targetClass, methodName);
-
if(m != null) {
-
TargetDataSource choDs = m.getAnnotation(TargetDataSource.class);
-
return resolveDataSourceName(choDs);
-
}
-
returnnull;
-
}
-
-
/**
-
* @param classDS
-
* @param methodDS
-
* @return
-
*/
-
privateString determinateDataSource(String classDS, String methodDS) {
-
return methodDS == null? classDS : methodDS;
-
}
-
-
/**
-
* @param targetClass
-
* @return
-
*/
-
privateString resolveDataSourceFromClass(Class targetClass) {
-
TargetDataSource classAnnotation = (TargetDataSource) targetClass.getAnnotation(TargetDataSource.class);
-
returnnull!= classAnnotation ? resolveDataSourceName(classAnnotation) : null;
-
}
-
-
/**
-
* @param ds
-
* @return
-
*/
-
privateString resolveDataSourceName(TargetDataSource ds) {
-
return ds == null? null: ds.value();
-
}
-
}