01:在
project中配置多个数据源
class="java" name="code">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">
</property>
<property name="url" value="jdbc:jtds:sqlserver://10.82.81.51:1433;databaseName=standards">
</property>
<property name="username" value="youguess"></property>
<property name="password" value="youguess"></property>
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">
</property>
<property name="url" value="jdbc:jtds:sqlserver://10.82.81.52:1433;databaseName=standards">
</property>
<property name="username" value="youguess"></property>
<property name="password" value="youguess"></property>
</bean>
02写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法
package com.qingce.appweb.java.control.datasource;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
protected Object determineCurrentLookupKey() {
return CustomerContextHolder.getCustomerType();
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
}
03:利用ThreadLocal解决
线程安全问题
package com.zbb.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();
}
}
04:再次配置数据源
<bean id="dynamicDataSource" class="com.zbb.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>
05:daoImpl中调用
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);
或
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_A);
参考学习http://www.cnb
logs.com/davidwang456/p/4318303.html