原来写过一篇关于SSM多数据源配置的博客,为什么今天又要写一篇呢?当然是因为需求的变更(蹭访问量),原来的博客中,多个数据源是配置在xml文件中的,每一个数据源都对应了一个会话管理器dataSource,这样就把数据源的数量给订死了,你有几个会话管理器就有几个数据源,不太方便,所以这次想达到一个动态添加删除数据源的效果.
原来的博文请见 MyBatis 配置多数据源实现多个数据库动态切换_mybitias 多库切换-优快云博客 写的反正也不咋地
1.创建存放数据源信息的实体类
/**
* 数据源实体类
*/
public class SourceEntity {
private String url;
private String username;
private String password;
private String driver;
private String type;
private String beanKey;
public SourceEntity(String type,String driver,String url, String username, String password,String beanKey ) {
this.url = url;
this.username = username;
this.password = password;
this.driver = driver;
this.type = type;
this.beanKey = beanKey;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBeanKey() {
return beanKey;
}
public void setBeanKey(String beanKey) {
this.beanKey = beanKey;
}
}
2.创建 CustomerContextHolder ,用于切换数据源信息和清除数据源信息
public class CustomerContextHolder {
public static final String DATASOURCE_DEFAULT = "dataSource";
public static final String DATASOURCE_REGION = "dataSourceRegion";
private static ThreadLocal<String> contentHolder = new ThreadLocal<>();
public static String getCustomerType() {
return contentHolder.get();
}
public static void setCustomerType(String customerType) {
contentHolder.set(customerType);
}
public static void clearCustomerType() {
contentHolder.remove();
}
}
3.在mybatis.xml 文件中添加下面的配置 ,dataSource 为你的主数据库,主数据库还是使用xml配置的方式
<!--动态数据源配置-->
<bean id="dynamicDataSource" class="com.mlkj.common.config.dataSourceConfig.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!--现有数据源-->
<entry value-ref="dataSource" key="dataSource"/>
</map>
</property>
<!--默认数据源-->
<property name="defaultTargetDataSource" ref="dataSource"/>
</bean>
4.在 sqlSessionFactory 的 dataSource中引入 3 中的数据源配置
<!-- MyBatis begin -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource"/>
<property name="typeAliasesPackage" value="com.mlkj"/>
<property name="typeAliasesSuperType" value="com.mlkj.common.persistence.BaseEntity"/>
<property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>
<property name=&#