AbstractRoutingDataSource
该类充当了DataSource的路由中介, 在运行时, 根据key值来动态切换到真正的DataSource上。通过继承该类,重写determineCurrentLookupKey方法,实现数据源的切换。
spring配置文件:
<!-- 配置多个数据源 -->
<bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test1?userUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"></property>
</bean>
<bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test2?userUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"></property>
</bean>
<!-- 继承AbstractRoutingDataSource的数据源路由类 -->
<bean id="dynamicDataSource" class="com.learn.moreDate.DynamicDataSource" >
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 根据不同的key值,选择不同的数据源 -->
<entry value-ref="dataSource1" key="dataSource1"></entry>
<entry value-ref="dataSource2" key="dataSource2"></entry>
</map>
</property>
<!-- 默认数据源 -->
<property name="defaultTargetDataSource" ref="dataSource1">
</property>
</bean>
数据源路由类:
package com.learn.moreDate;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return CustomerContextHolder.getCustomerType();
}
}
key值存储类:
package com.learn.moreDate;
public class CustomerContextHolder {
//数据源对应key值,与配置文件中key值相同
public static final String DATA_A = "dataSource1";
public static final String DATA_B = "dataSource2";
//存储当前线程的key值
private static final ThreadLocal<String> contextHolder = new ThreadLocal();
public static void setCustomerType(String customerType)
{
contextHolder.set(customerType);
}
public static String getCustomerType()
{
return contextHolder.get();
}
public static void clearCustomerType()
{
contextHolder.remove();
}
}
测试类:
package com.learn.moreDate;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class Demo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");
//设置数据源对应key值
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_B);
//获取数据源
DataSource dds = (DataSource)context.getBean("dynamicDataSource");
//执行sql
JdbcTemplate template = new JdbcTemplate(dds);
String sql = "delete from work";
template.update(sql);
}
}