Spring Dynamic DataSource Routing

本文介绍了一种使用Spring框架下的AbstractRoutingDataSource实现动态数据源切换的方法。通过自定义DynamicDataSource类,可以根据不同的业务需求选择相应的数据库连接。示例中展示了如何配置两个不同的Oracle数据源,并在运行时动态地进行切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

參考資料:
[url=http://xuganggogo.iteye.com/blog/1461489]spring动态数据源的切换[/url]
[url=http://fxiaozj.iteye.com/blog/1420833]Spring动态切换数据源[/url]
[url=http://exceptioneye.iteye.com/blog/1698064]利用AbstractRoutingDataSource实现动态数据源切换 (一、Spring+Hibernate)[/url]
[url=http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/]DYNAMIC DATASOURCE ROUTING[/url] :idea:


package tamino.tsai.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSourceType();
}

}


package tamino.tsai.config;

import tamino.tsai.enums.DataSourceType;

public class DynamicDataSourceHolder {
private static final ThreadLocal<DataSourceType> contextHolder = new ThreadLocal<DataSourceType>();

// 設置DB類型
public static void setDataSourceType(DataSourceType dataSourceType) {
//Assert.notNull(dataSourceType, "DataSourceType cannot be null");
contextHolder.set(dataSourceType);
}

// 獲取DB類型
public static DataSourceType getDataSourceType() {
return (DataSourceType) contextHolder.get();
}

// 清除DB類型
public static void clearDataSourceType() {
contextHolder.remove();
}
}


package tamino.tsai.enums;

public enum DataSourceType {
KEYA,
KEYB
}


<bean id="baseDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@host1:port:abc" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>

<bean id="aDataSource" parent="baseDataSource">
<property name="url" value="jdbc:oracle:thin:@host1:port:abc" />
</bean>
<bean id="bDataSource" parent="baseDataSource">
<property name="url" value="jdbc:oracle:thin:@host2:port:abc" />
</bean>

<bean id="dataSource" class="tamino.tsai.config.DynamicDataSource">
<property name="targetDataSources">
<map key-type="tamino.tsai.enums.DataSourceType">
<entry key="KEYA" value-ref="aDataSource"></entry>
<entry key="KEYB" value-ref="bDataSource"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="uatDataSource">
</property>
</bean>
<bean id="myDao" class="tamino.tsai.dao.impl.MyDaoImpl">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值