Spring多数据源的动态切换

目前很多项目中只能配置单个数据源,那么如果有多个数据源肿么办?Spring提供了一个抽象类AbstractRoutingDataSource,为我们很方便的解决了这个问题。
1.写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法
public class DynamicDataSource extends AbstractRoutingDataSource{
 private final static Logger  logger  = LoggerFactory.getLogger("DynamicDataSource");   
 
    @Override  
    protected Object determineCurrentLookupKey() {   
        return DbContextHolder.getDbType();   
    }   
}


2.写一个线程安全的ThreadLocal

public class DbContextHolder { private static final ThreadLocal contextHolder = new ThreadLocal(); public static void setDbType(String dbType) { contextHolder.set(dbType); } public static String getDbType() { return (String) contextHolder.get(); } public static void clearDbType() { contextHolder.remove(); } }


3.dataSource的配置
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire="byName">

<bean id="aTestDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${a.jdbc.driverClassName}" />
<property name="url" value="${a.jdbc.url}" />
<property name="username" value="${a.jdbc.username}" />
<property name="password" value="${a.jdbc.password}" />
</bean>

<bean id="bTestDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${b.jdbc.driverClassName}" />
<property name="url" value="${gott.jdbc.url}" />
<property name="username" value="${b.jdbc.username}" />
<property name="password" value="${b.jdbc.password}" />
</bean>

<bean id="dataSource" class="***.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="aTestDataSource" value-ref="aTestDataSource" />
<entry key="bTestDataSource" value-ref="bTestDataSource" />
</map>
</property>
<property name="aTestDataSource" ref="aTestDataSource" />
</bean>
</beans>


4.当需要切换数据源时,只要调用一行代码就可以了

DbContextHolder.setDbType("aTestDataSource");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值