多数据源问题很常见,例如读写分离数据库配置。
原来的项目出现了新需求,局方要求新增某服务器用以提供某代码,涉及到多数据源的问题。
研究成果如下:
1、首先配置多个datasource
2、写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法
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解决线程安全问题
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 ThreadLocalcontextHolder = new ThreadLocal (); public static void setCustomerType(String customerType) { contextHolder.set(customerType); } public static String getCustomerType() { return contextHolder.get(); } public static void clearCustomerType() { contextHolder.remove(); }}
4、数据源配置
5、在DAOImpl中切换数据源
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);
搞定!