哄骗Spring的AbstractRoutingDataSource解决多半据源的题目

    添加时间:2013-7-10 点击量:

    多半据源题目很常见,例如读写分别数据库设备。


    本来的项目呈现了新需求,局方请求新增某办事器用以供给某代码,涉及到多半据源的题目。


    解决办法如下:


    1、起首设备多个datasource



     1 <bean id=dataSource class=org.apache.commons.dbcp.BasicDataSource>
    
    2 <property name=driverClassName value=net.sourceforge.jtds.jdbc.Driver>
    3 </property>
    4 <property name=url value=jdbc:jtds:sqlserver://10.82.81.51:1433;databaseName=standards>
    5 </property>
    6 <property name=username value=youguess></property>
    7 <property name=password value=youguess></property>
    8 </bean>
    9 <bean id=dataSource2 class=org.apache.commons.dbcp.BasicDataSource>
    10 <property name=driverClassName value=net.sourceforge.jtds.jdbc.Driver>
    11 </property>
    12 <property name=url value=jdbc:jtds:sqlserver://10.82.81.52:1433;databaseName=standards>
    13 </property>
    14 <property name=username value=youguess></property>
    15 <property name=password value=youguess></property>
    16 </bean>


    2、写一个DynamicDataSource类持续AbstractRoutingDataSource,并实现determineCurrentLookupKey办法




    1 package com.standard.core.util;
    
    2 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    3 public class DynamicDataSource extends AbstractRoutingDataSource {
    4 @Override
    5 protected Object determineCurrentLookupKey() {
    6 return CustomerContextHolder.getCustomerType();
    7 }
    8 }



    3、哄骗ThreadLocal解决线程安然题目




     1 package com.standard.core.util;
    
    2 public class CustomerContextHolder {
    3 public static final String DATA_SOURCE_A = dataSource;
    4 public static final String DATA_SOURCE_B = dataSource2;
    5 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    6 public static void setCustomerType(String customerType) {
    7 contextHolder.set(customerType);
    8 }
    9 public static String getCustomerType() {
    10 return contextHolder.get();
    11 }
    12 public static void clearCustomerType() {
    13 contextHolder.remove();
    14 }
    15 }





    4、数据源设备





     1 <bean id=dynamicDataSource class=com.standard.core.util.DynamicDataSource >
    
    2 <property name=targetDataSources>
    3 <map key-type=java.lang.String>
    4 <entry value-ref=dataSource key=dataSource></entry>
    5 <entry value-ref=dataSource2 key=dataSource2></entry>
    6 </map>
    7 </property>
    8 <property name=defaultTargetDataSource ref=dataSource >
    9 </property>
    10 </bean>


    5、在DAOImpl中切换数据源



    1 CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B); 



    我们永远不要期待别人的拯救,只有自己才能升华自己。自己已准备好了多少容量,方能吸引对等的人与我们相遇,否则再美好的人出现、再动人的事情降临身边,我们也没有能量去理解与珍惜,终将擦肩而过。—— 姚谦《品味》
    分享到: