利用Spring的AbstractRoutingDataSource解决多数据源的问题

多数据源问题很常见,例如读写分离数据库配置。

原来的项目出现了新需求,局方要求新增某服务器用以提供某代码,涉及到多数据源的问题。

研究成果如下:

1、首先配置多个datasource



2、写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法





3、利用ThreadLocal解决线程安全问题

[java]  view plain  copy
  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 contextHolder = new ThreadLocal();  
  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、数据源 配置

[html]  view plain  copy
  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中切换数据源

[java]  view plain  copy
  1. CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);   

搞定!

你可能感兴趣的:(spring)