spring 多数据源
之前尝试的一个多数据源切换的功能测试可以实现了,下面进行一下简单的笔记
applicationContext-mapper.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
TestService 方法通过以下方式进行主动切换
DynamicDataSource.updateData(DynamicDataSource.DATA_SOURCE_MYSQL);
Test loginUser = testMapper.selectTest(test);
DynamicDataSource.updateData(DynamicDataSource.DATA_SOURCE_ORACLE);
TestOracle oracle = testOracleMapper.selectTestOracle(Gkey);
DynamicDataSource 类
package com.utils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/*
* 配置多数据源
*/
public class DynamicDataSource extends AbstractRoutingDataSource{
public static final String DATA_SOURCE_MYSQL = "dataSource_mysql";
public static final String DATA_SOURCE_ORACLE = "dataSource_oracle";
//本地线程,获取当前正在执行的currentThread
public static final ThreadLocal
public static void setCustomerType(String customerType) {
contextHolder.set(customerType);
}
public static String getCustomerType() {
return contextHolder.get();
}
public static void clearCustomerType() {
contextHolder.remove();
}
@Override
protected Object determineCurrentLookupKey() {
return getCustomerType();
}
public static void updateData(String dataSN){
DynamicDataSource.clearCustomerType();//重点: 实际操作证明,切换的时候最好清空一下
DynamicDataSource.setCustomerType(dataSN);//切换数据源,设置后 就OK了。可以随时切换过来(在controller层切换)
DynamicDataSource.getCustomerType();
}
}
目前发现在同一方法内访问同一数据源 不需要进行切换数据源
在同一方法内访问不同数据源,非默认数据源的需要切换,切换后不需要恢复默认数据源
切换后的数据源的访问影响,该方法下次访问时的数据源,原因应该和方法的存储空间有关系?目前还没搞清楚