AbstractRoutingDataSource 是spring提供的一个多数据源抽象类。spring会在使用事务的地方来调用此类的determineCurrentLookupKey()方法来获取数据源的key值。咱们继承此抽象类并实现此方法:java
package com.ctitc.collect.manage.datasource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; /** * * @author zongbo * 实现spring多路由配置,由spring调用 */ public class DataSourceRouter extends AbstractRoutingDataSource { // 获取数据源名称 protected Object determineCurrentLookupKey() { return HandleDataSource.getDataSource(); } }
DataSourceRouter 类中经过HandleDataSource.getDataSource()获取数据源的key值。此方法应该和线程绑定。spring
package com.ctitc.collect.manage.datasource; /** * 线程相关的数据源处理类 * @author zongbo * */ public class HandleDataSource { // 数据源名称线程池 private static final ThreadLocal<String> holder = new ThreadLocal<String>(); /** * 设置数据源 * @param datasource 数据源名称 */ public static void setDataSource(String datasource) { holder.set(datasource); } /** * 获取数据源 * @return 数据源名称 */ public static String getDataSource() { return holder.get(); } /** * 清空数据源 */ public static void clearDataSource() { holder.remove(); } }
对于spring来讲,注解即简单方便且可读性也高。因此,咱们也经过注解在service的方法前指定所用的数据源。咱们先定义本身的注解类,其中value为数据源的key值。sql
package com.ctitc.collect.manage.datasource; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 数据源注解类 * @author zongbo * */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface DataSource { String value(); }
指定注解之后,咱们能够经过AOP拦截全部service方法,在方法执行以前获取方法上的注解:即数据源的key值。数据库
package com.ctitc.collect.manage.datasource; import java.lang.reflect.Method; import java.text.MessageFormat; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; /** * 切换数据源(不一样方法调用不一样数据源) */ @Aspect @Component @Order(1) //请注意:这里order必定要小于tx:annotation-driven的order,即先执行DataSourceAspect切面,再执行事务切面,才能获取到最终的数据源 @EnableAspectJAutoProxy(proxyTargetClass = true) public class DataSourceAspect { static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class); /** * 切入点 service包及子孙包下的全部类 */ @Pointcut("execution(* com.ctitc.collect.service..*.*(..))") public void aspect() { } /** * 配置前置通知,使用在方法aspect()上注册的切入点 */ @Before("aspect()") public void before(JoinPoint point) { Class<?> target = point.getTarget().getClass(); MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod() ; DataSource dataSource = null ; //从类初始化 dataSource = this.getDataSource(target, method) ; //从接口初始化 if(dataSource == null){ for (Class<?> clazz : target.getInterfaces()) { dataSource = getDataSource(clazz, method); if(dataSource != null){ break ;//从某个接口中一旦发现注解,再也不循环 } } } if(dataSource != null && !StringUtils.isEmpty(dataSource.value()) ){ HandleDataSource.setDataSource(dataSource.value()); } } @After("aspect()") public void after(JoinPoint point) { //使用完记得清空 HandleDataSource.setDataSource(null); } /** * 获取方法或类的注解对象DataSource * @param target 类class * @param method 方法 * @return DataSource */ public DataSource getDataSource(Class<?> target, Method method){ try { //1.优先方法注解 Class<?>[] types = method.getParameterTypes(); Method m = target.getMethod(method.getName(), types); if (m != null && m.isAnnotationPresent(DataSource.class)) { return m.getAnnotation(DataSource.class); } //2.其次类注解 if (target.isAnnotationPresent(DataSource.class)) { return target.getAnnotation(DataSource.class); } } catch (Exception e) { e.printStackTrace(); logger.error(MessageFormat.format("经过注解切换数据源时发生异常[class={0},method={1}]:" , target.getName(), method.getName()),e) ; } return null ; } }
假设我有两个库:业务库和订单库。先要配置这两个数据源并发
<bean id="busiDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <description>业务数据源</description> <!-- 数据库基本信息配置 --> <property name="driverClassName" value="${busi.driverClassName}" /> <property name="url" value="${busi.url}" /> <property name="username" value="${busi.username}" /> <property name="password" value="${busi.password}" /> <!-- 初始化链接数量 --> <property name="initialSize" value="${druid.initialSize}" /> <!-- 最大并发链接数 --> <property name="maxActive" value="${druid.maxActive}" /> <!-- 最小空闲链接数 --> <property name="minIdle" value="${druid.minIdle}" /> <!-- 配置获取链接等待超时的时间 --> <property name="maxWait" value="${druid.maxWait}" /> <!-- 超过期间限制是否回收 --> <property name="removeAbandoned" value="${druid.removeAbandoned}" /> <!-- 超过期间限制多长; --> <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" /> <!-- 配置间隔多久才进行一次检测,检测须要关闭的空闲链接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" /> <!-- 配置一个链接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" /> <!-- 用来检测链接是否有效的sql,要求是一个查询语句--> <property name="validationQuery" value="${druid.validationQuery}" /> <!-- 申请链接的时候检测 --> <property name="testWhileIdle" value="${druid.testWhileIdle}" /> <!-- 申请链接时执行validationQuery检测链接是否有效,配置为true会下降性能 --> <property name="testOnBorrow" value="${druid.testOnBorrow}" /> <!-- 归还链接时执行validationQuery检测链接是否有效,配置为true会下降性能 --> <property name="testOnReturn" value="${druid.testOnReturn}" /> <!-- 打开PSCache,而且指定每一个链接上PSCache的大小 --> <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" /> <!--属性类型是字符串,经过别名的方式配置扩展插件,经常使用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防护SQL注入的filter:wall --> <property name="filters" value="${druid.filters}" /> </bean>
<bean id="orderDataSource" class="com.alibaba.druid.pool.DruidDataSource" parent="busiDataSource"> <description>订单数据源</description> <property name="driverClassName" value="${order.driverClassName}" /> <property name="url" value="${order.url}" /> <property name="username" value="${order.username}" /> <property name="password" value="${order.password}" /> </bean>
targetDataSources :数据源列表,key-value形式,即上面配置的两个数据源
defaultTargetDataSource:默认数据源,若是未指定数据源 或者指定的数据源不存在的话 默认使用这个数据源app
<bean id="dataSource" class="com.ctitc.collect.manage.datasource.DataSourceRouter" lazy-init="true"> <description>多数据源路由</description> <property name="targetDataSources"> <map key-type="java.lang.String" value-type="javax.sql.DataSource"> <!-- write --> <entry key="busi" value-ref="busiDataSource" /> <entry key="order" value-ref="orderDataSource" /> </map> </property> <!-- 默认数据源,若是未指定数据源 或者指定的数据源不存在的话 默认使用这个数据源 --> <property name="defaultTargetDataSource" ref="busiDataSource" /> </bean>
因为我使用的注解式事务,和咱们的AOP数据源切面有一个顺序的关系。数据源切换必须先执行,数据库事务才能获取到正确的数据源。因此要明确指定 注解式事务和 咱们AOP数据源切面的前后顺序。ide
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" order="2" />
在每一个service方法前使用@DataSource("数据源key")注解便可。性能
@Override @DataSource("busi") @Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public List<BasVersion> test1() { // TODO Auto-generated method stub return coreMapper.getVersion(); } @Override @DataSource("order") @Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public List<BasVersion> test2() { // TODO Auto-generated method stub return coreMapper.getVersion(); }