分享

Spring多数据源的动态切换

 roydocs 2013-09-12
目前很多项目中只能配置单个数据源,那么如果有多个数据源肿么办?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./schema/beans" xmlns:xsi="http://www./2001/XMLSchema-instance"
xmlns:p="http://www./schema/p" xmlns:context="http://www./schema/context"
xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-2.5.xsd
http://www./schema/context http://www./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");

当然有兴趣的朋友也可以用aop去自动切换数据源

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约