首页 > 代码库 > 利用Spring的AbstractRoutingDataSource解决多数据源的问题(转)
利用Spring的AbstractRoutingDataSource解决多数据源的问题(转)
多数据源问题很常见,例如读写分离数据库配置。
原来的项目出现了新需求,局方要求新增某服务器用以提供某代码,涉及到多数据源的问题。
研究成果如下:
1、首先配置多个datasource
[html] view plaincopy
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value=http://www.mamicode.com/"net.sourceforge.jtds.jdbc.Driver">
- </property>
- <property name="url" value=http://www.mamicode.com/"jdbc:jtds:sqlserver://10.82.81.51:1433;databaseName=standards">
- </property>
- <property name="username" value=http://www.mamicode.com/"youguess"></property>
- <property name="password" value=http://www.mamicode.com/"youguess"></property>
- </bean>
- <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value=http://www.mamicode.com/"net.sourceforge.jtds.jdbc.Driver">
- </property>
- <property name="url" value=http://www.mamicode.com/"jdbc:jtds:sqlserver://10.82.81.52:1433;databaseName=standards">
- </property>
- <property name="username" value=http://www.mamicode.com/"youguess"></property>
- <property name="password" value=http://www.mamicode.com/"youguess"></property>
- </bean>
2、写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法
[java] view plaincopy
- package com.standard.core.util;
- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
- public class DynamicDataSource extends AbstractRoutingDataSource {
- @Override
- protected Object determineCurrentLookupKey() {
- return CustomerContextHolder.getCustomerType();
- }
- }
3、利用ThreadLocal解决线程安全问题
[java] view plaincopy
- package com.standard.core.util;
- public class CustomerContextHolder {
- public static final String DATA_SOURCE_A = "dataSource";
- public static final String DATA_SOURCE_B = "dataSource2";
- private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
- public static void setCustomerType(String customerType) {
- contextHolder.set(customerType);
- }
- public static String getCustomerType() {
- return contextHolder.get();
- }
- public static void clearCustomerType() {
- contextHolder.remove();
- }
- }
4、数据源配置
[html] view plaincopy
- <bean id="dynamicDataSource" class="com.standard.core.util.DynamicDataSource" >
- <property name="targetDataSources">
- <map key-type="java.lang.String">
- <entry value-ref="dataSource" key="dataSource"></entry>
- <entry value-ref="dataSource2" key="dataSource2"></entry>
- </map>
- </property>
- <property name="defaultTargetDataSource" ref="dataSource" >
- </property>
- </bean>
5、在DAOImpl中切换数据源
[java] view plaincopy
- CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);
搞定!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。