标签:spring 连接池切换 读写分离
spring有提供AbstractRoutingDataSource类来实现数据源的动态切换,用来实现读写分离也自然没什么问题了。
实现原理:扩展Spring的AbstractRoutingDataSource抽象类(该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上。)
从AbstractRoutingDataSource的源码中:
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean
我们可以看到,它继承了AbstractDataSource,而AbstractDataSource是javax.sql.DataSource的子类,我们可以分析下它的getConnection方法:
public Connection getConnection() throws SQLException { return determineTargetDataSource().getConnection(); } public Connection getConnection(String username, String password) throws SQLException { return determineTargetDataSource().getConnection(username, password); }
获取连接的方法中,重点是determineTargetDataSource()方法,看源码:
/** * Retrieve the current target DataSource. Determines the * {@link #determineCurrentLookupKey() current lookup key}, performs * a lookup in the {@link #setTargetDataSources targetDataSources} map, * falls back to the specified * {@link #setDefaultTargetDataSource default target DataSource} if necessary. * @see #determineCurrentLookupKey() */ protected DataSource determineTargetDataSource() { Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); Object lookupKey = determineCurrentLookupKey(); DataSource dataSource = this.resolvedDataSources.get(lookupKey); if (dataSource == null && (this.lenientFallback || lookupKey == null)) { dataSource = this.resolvedDefaultDataSource; } if (dataSource == null) { throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]"); } return dataSource; }
上面这段源码的重点在于determineCurrentLookupKey()方法,这是AbstractRoutingDataSource类中的一个抽象方法,而它的返回值是你所要用的数据源dataSource的key值,有了这个key值,resolvedDataSource(这是个map,由配置文件中设置好后存入的)就从中取出对应的DataSource,如果找不到,就用配置默认的数据源。
扩展AbstractRoutingDataSource类,并重写其中的determineCurrentLookupKey()方法,来实现数据源的切换:
实战:
扩展AbstractRoutingDataSource,传递不同数据源
package org.scf.db;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 扩展spring route data source
* @author scf
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return CustomerContextHolder.getCustomerType();
}
}
package org.scf.db;
public class CustomerContextHolder {
public static final String DATA_SOURCE_READ = "dataSourceRead";
public static final String DATA_SOURCE_WRITE = "dataSourceWrite";
private static 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();
}
}
配置spring文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 定义受环境影响易变的变量 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<!-- 标准配置 -->
<value>classpath:application.properties</value>
</list>
</property>
</bean>
<bean id="dataSourceWrite" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver.write}"/>
<property name="url" value="${jdbc.url.write}"/>
<property name="username" value="${jdbc.username.write}"/>
<property name="password" value="${jdbc.password.write}"></property>
</bean>
<bean id="dataSourceRead" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver.read}"/>
<property name="url" value="${jdbc.url.read}"/>
<property name="username" value="${jdbc.username.read}"/>
<property name="password" value="${jdbc.password.read}"></property>
</bean>
<!-- 动态数据源 -->
<bean id="dynamicDataSource" class="org.scf.db.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSourceRead" key="dataSourceRead"></entry>
<entry value-ref="dataSourceWrite" key="dataSourceWrite"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceWrite">
</property>
</bean>
<!-- 启用aop -->
<aop:aspectj-autoproxy/>
<!-- 启用 annotation -->
<context:annotation-config/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<!-- 默认是写数据源,程序中将其改为读数据源 -->
<ref bean="dynamicDataSource"/>
</property>
</bean>
<bean id="db" class="org.scf.db.TemplateManager"></bean>
</beans>
建立模板接口package org.scf.db;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
public interface DBManager {
public JdbcTemplate getTemplate();
/**
* 插入/更新/删除
*
* @param sql
* @param args
* @return 本次更新影响的行数
*/
public int update(String sql, Object[] args);
/**
* 查询列表
*
* @param sql
* @param args
* @return 查询的数据列表
*/
public List<Map<String, Object>> queryForList(String sql, Object[] args);
}
package org.scf.db;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class TemplateManager implements DBManager{
@Autowired
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
/**
* 插入/更新/删除
*
* @param sql
* @param args
* @return 本次更新影响的行数
*/
@Override
public int update(String sql, Object[] args) {
int result = -1;
result = template.update(sql, args);
return result;
}
/**
* 查询列表
*
* @param sql
* @param args
* @return 查询的数据列表
*/
@Override
public List<Map<String, Object>> queryForList(String sql, Object[] args) {
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_READ);//切换数据源,默认是写连接池,此处修改成读连接池
List<Map<String, Object>> result = null;
result = template.queryForList(sql, args);
return result;
}
}
测试
package org.scf.test;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import org.scf.db.DBManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class RouteTestJ {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DBManager db = (DBManager)context.getBean("db");
@Test
public void insertTest(){//写连接池
String sql = "insert into scfTest values (4)";
db.update(sql, null);
}
@Test
public void searchTest(){//读连接池
String sql = "select id from scfTest";
List list = db.queryForList(sql, null);
System.out.println(list.size());
}
}
spring AbstractRoutingDataSource 实现读写分离
标签:spring 连接池切换 读写分离
原文地址:http://luzhishen.blog.51cto.com/1813539/1651847