目前基本都是SpringBoot项目的走遍天下了,很少接触到 SpringMvc+Mybatis项目,而最近碰到记录一下
配置多个数据源
找到配置数据源的xml文件 调整如下:
<!-- 需要在Tomcat,content.xml中配置数据源 -->
<bean id="oneDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="oneDataSource"/>
</bean>
<bean id="twoDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="twoDataSource"/>
</bean>
<!-- 配置数据库切换类 -->
<bean id="dynamicDataSource" class="cn.com.xxx.common.datasource.DynamicDataSource">
<!-- 设置默认数据源 -->
<property name="defaultTargetDataSource" ref="oneDataSource"/>
<property name="targetDataSources">
<map>
<entry key="oneDataSource" value-ref="oneDataSource"/>
<entry key="twoDataSource" value-ref="twoDataSource"></entry>
</map>
</property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource" />
<property name="mapperLocations" value="classpath*:cn/com/xxx/common/mapper
新增另个java类 DynamicDataSource.java和DataSourceHolder.java
DynamicDataSource.java
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSourceType();
}
}
DataSourceHolder.java
public class DataSourceHolder {
public static final String ONE_DATA_SOURCE ="oneDataSource";
public static final String TWO_DATA_SOURCE ="twoDataSource";
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
return contextHolder.get();
}
public static void clearDataSourceType() {
contextHolder.remove();
}
public static void changeCurrentDataSource(String dataSourceType) {
clearDataSourceType();
setDataSourceType(dataSourceType);
}
public static void changeCurrentDataSource() {
clearDataSourceType();
}
}
最后在访问数据库前:添加 DataSourceHolder.changeCurrentDataSource(DataSourceHolder.TWO_DATA_SOURCE); 即可。
|