public class MultiDataSource extends AbstractRoutingDataSource {
private static final Logger logger = Logger.getLogger(MultiDataSource.class);
private Object[] targetDataSourcesKeys = null;
private static final ThreadLocal<Object> contextHolder = new ThreadLocal<Object>();
public static void setCurrentLookupKeyIndex(Integer currentLookupKeyIndex) {
Assert.notNull(currentLookupKeyIndex,
"current LookupKey cannot be null");
contextHolder.set(currentLookupKeyIndex);
}
public static Integer getCurrentLookupKeyIndex() {
Integer i = (Integer) contextHolder.get();
if (i == null) {
setCurrentLookupKeyIndex(0);
return new Integer(0);
} else {
return i;
}
}
public static void clearCurrentLookupKeyIndex() {
contextHolder.remove();
}
protected Object determineCurrentLookupKey() {
return targetDataSourcesKeys[getCurrentLookupKeyIndex().intValue()];
}
public Connection getConnection() throws SQLException{
setCurrentLookupKeyIndex(0);
for(int i=0 ; i<targetDataSourcesKeys.length ;){
try{
Connection conn = determineTargetDataSource().getConnection();
logger,info("now datasourse is ***********########"+targetDataSourcesKeys[i]);
//获取连接成功
return conn;
}catch(Exception e){
//获取连接失败
setCurrentLookupKeyIndex(++i);
}
}
return determineTargetDataSource().getConnection();
}
public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {
super.setDataSourceLookup(dataSourceLookup);
}
public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
}
public void setTargetDataSources(Map targetDataSources) {
this.targetDataSourcesKeys = targetDataSources.keySet().toArray();
setCurrentLookupKeyIndex(0);
super.setTargetDataSources(targetDataSources);
}
}
Spring配置
<bean id="myds1" class="org.springframework.jndi.JndiObjectFactoryBean" destroy-method="close">
<property name="jndiName">
<value>myds1</value>
</property>
</bean>
<bean id="myds2" class="org.springframework.jndi.JndiObjectFactoryBean" destroy-method="close">
<property name="jndiName">
<value>myds2</value>
</property>
</bean>
<bean id="myds3" class="org.springframework.jndi.JndiObjectFactoryBean" destroy-method="close">
<property name="jndiName">
<value>myds3</value>
</property>
</bean>
<util:map id="ourDs">
<entry key="ds1" value-ref="myds1" />
<entry key="ds2" value-ref="myds2" />
<entry key="ds3" value-ref="myds3" />
</util:map>
<bean id="dataSourceLookup" class="org.springframework.jdbc.datasource.lookup.MapDataSourceLookup">
<constructor-arg>
<ref bean="ourDs" />
</constructor-arg>
</bean>
<bean id="myDs" class="com.test.MultiDataSource">
<property name="defaultTargetDataSource" ref="myds1" />
<property name="targetDataSources" ref="ourDs" />
<property name="dataSourceLookup" ref="dataSourceLookup" />
</bean>