作者:suroot

spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性。而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时的请求及系统状态来动态的决定将数据存储在哪个数据库实例中,以及从哪个数据库提取数据。
Spring2.x以后的版本中采用Proxy模式,就是我们在方案中实现一个虚拟的数据源,并且用它来封装数据源选择逻辑,这样就可以有效地将数据源选择逻辑从Client中分离出来。Client提供选择所需的上下文(因为这是Client所知道的),由虚拟的DataSource根据Client提供的上下文来实现数据源的选择。
实现
具体的实现就是,虚拟的DataSource仅需继承AbstractRoutingDataSource实现determineCurrentLookupKey()在其中封装数据源的选择逻辑。

1.动态配置多数据源
数据源的名称常量和一个获得和设置上下文环境的类,主要负责改变上下文数据源的名称

public class DataSourceContextHolder {

    public static final String DATA_SOURCE_A = "dataSourceA";
public static final String DATA_SOURCE_B = "dataSourceB";
public static final String DATA_SOURCE_C = "dataSourceC";
public static final String DATA_SOURCE_D = "dataSourceD";
// 线程本地环境
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); // 设置数据源类型
public static void setDbType(String dbType) {
// System.out.println("此时切换的数据源为:"+dbType);
contextHolder.set(dbType);
}
// 获取数据源类型
public static String getDbType() {
return (contextHolder.get());
}
// 清除数据源类型
public static void clearDbType() {
contextHolder.remove();
}
}

2.建立动态数据源类,注意,这个类必须继承AbstractRoutingDataSource,且实现方法determineCurrentLookupKey,该方法返回一个Object,一般是返回字符串:

public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
System.out.println("此时获取到的数据源为:"+DataSourceContextHolder.getDbType());
return DataSourceContextHolder.getDbType();
}
}

为了更好的理解为什么会切换数据源,我们来看一下AbstractRoutingDataSource.java源码,源码中确定数据源部分主要内容如下

    /**
* 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()方法,来实现数据源的切换:

3.编写spring的配置文件配置多个数据源

    <!-- 配置数据源  dataSourceA-->
<bean name="dataSourceA" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 -->
<property name="initialSize" value="20" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="500" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" /> <property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="1000" /> <!-- 监控数据库 -->
<!--<property name="filters" value="stat,log4j"/>-->
<property name="filters" value="stat" />
</bean> <!-- 配置数据源 dataSourceB -->
<bean name="dataSourceB" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_new_url}" />
<property name="username" value="${jdbc_new_username}" />
<property name="password" value="${jdbc_new_password}" />
<property name="initialSize" value="10" />
<property name="maxActive" value="100" />
<property name="maxIdle" value="10" />
<property name="minIdle" value="0" />
<property name="maxWait" value="10000" />
<property name="validationQuery" value="${validationQuery3}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="25200000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="1800" />
<property name="logAbandoned" value="true" />
<property name="filters" value="stat" />
</bean> <!-- 配置数据源 dataSourceC -->
<bean name="dataSourceC" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_mysql_url}" />
<property name="username" value="${jdbc_mysql_username}" />
<property name="password" value="${jdbc_mysql_password}" />
<property name="initialSize" value="10" />
<property name="maxActive" value="100" />
<property name="maxIdle" value="10" />
<property name="minIdle" value="0" />
<property name="maxWait" value="60000" />
<property name="validationQuery" value="${validationQuery2}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="25200000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="1800" />
<property name="logAbandoned" value="true" />
<property name="filters" value="stat" />
</bean> <!-- 多数据源配置 -->
<bean id="dataSource" class="top.suroot.base.datasource.DynamicDataSource">
<!-- 默认使用dataSourceA的数据源 -->
<property name="defaultTargetDataSource" ref="dataSourceA"></property>
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSourceA" key="dataSourceA"></entry>
<entry value-ref="dataSourceB" key="dataSourceB"></entry>
<entry value-ref="dataSourceC" key="dataSourceC"></entry>
<!--<entry value-ref="dataSourceD" key="dataSourceD"></entry>-->
</map>
</property>
</bean>

在这个配置中第一个property属性配置目标数据源,<map key-type="java.lang.String">中的key-type必须要和静态键值对照类DataSourceConst中的值的类型相 同;<entry key="User" value-ref="userDataSource"/>中key的值必须要和静态键值对照类中的值相同,如果有多个值,可以配置多个< entry>标签。第二个property属性配置默认的数据源。

4.动态切换是数据源

DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_B);

以上讲的是怎么动态切换数据源,下面要说下自定义注解、aop方式自动切换数据源 ,感兴趣的可以继续往下看看
5.配置自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface DynamicDataSourceAnnotation {
//dataSource 自定义注解的参数
String dataSource() default DataSourceContextHolder.DATA_SOURCE_A;
}

6.配置切面类

@Aspect
@Component
@Order(1)
public class DynamicDataSourceAspect { @Before("@annotation(top.suroot.base.aop.DynamicDataSourceAnnotation)") //前置通知
public void testBefore(JoinPoint point){
//获得当前访问的class
Class<?> className = point.getTarget().getClass();
DynamicDataSourceAnnotation dataSourceAnnotation = className.getAnnotation(DynamicDataSourceAnnotation.class);
if (dataSourceAnnotation != null ) {
//获得访问的方法名
String methodName = point.getSignature().getName();
//得到方法的参数的类型
Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DATA_SOURCE_A;
try {
Method method = className.getMethod(methodName, argClass);
if (method.isAnnotationPresent(DynamicDataSourceAnnotation.class)) {
DynamicDataSourceAnnotation annotation = method.getAnnotation(DynamicDataSourceAnnotation.class);
dataSource = annotation.dataSource();
System.out.println("DataSource Aop ====> "+dataSource);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataSourceContextHolder.setDbType(dataSource);
} } @After("@annotation(top.suroot.base.aop.DynamicDataSourceAnnotation)") //后置通知
public void testAfter(JoinPoint point){
//获得当前访问的class
Class<?> className = point.getTarget().getClass();
DynamicDataSourceAnnotation dataSourceAnnotation = className.getAnnotation(DynamicDataSourceAnnotation.class);
if (dataSourceAnnotation != null ) {
//获得访问的方法名
String methodName = point.getSignature().getName();
//得到方法的参数的类型
Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DATA_SOURCE_A;
try {
Method method = className.getMethod(methodName, argClass);
if (method.isAnnotationPresent(DynamicDataSourceAnnotation.class)) {
DynamicDataSourceAnnotation annotation = method.getAnnotation(DynamicDataSourceAnnotation.class);
dataSource = annotation.dataSource();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(dataSource != null && !DataSourceContextHolder.DATA_SOURCE_A.equals(dataSource)) DataSourceContextHolder.clearDbType();
}
}
}

7.在切入点添加自定义的注解

@Service("baseService")
@DynamicDataSourceAnnotation
public class BaseServiceImpl implements BaseService { @DynamicDataSourceAnnotation(dataSource = DataSourceContextHolder.DATA_SOURCE_B)
public void changeDataSource() {
System.out.println("切换数据源serviceImple");
}
}

8.当然注解扫描、和aop代理一定要在配置文件中配好

    <!-- 自动扫描(bean注入) -->
<context:component-scan base-package="top.suroot.*" />
<!-- AOP自动代理功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>

大功告成,当调用changeDataSource方法的时候会进入切面类中切换数据源,方法调用完毕会把数据源切换回来。

作者:suroot
链接:http://www.jianshu.com/p/ddebf4ae57c1
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出

Spring中AOP方式实现多数据源切换的更多相关文章

  1. Spring学习之Spring中AOP方式切入声明式事务

    mybatis-spring官方文档说明 一个使用 MyBatis-Spring 的其中一个主要原因是它允许 MyBatis 参与到 Spring 的事务管理中.而不是给 MyBatis 创建一个新的 ...

  2. Spring Boot数据访问之动态数据源切换之使用注解式AOP优化

    在Spring Boot数据访问之多数据源配置及数据源动态切换 - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中详述了如何配置多数据源及多数据源之间的动态切换.但是需要读数据库的地方,就 ...

  3. JAVA高级架构师基础功:Spring中AOP的两种代理方式:动态代理和CGLIB详解

    在spring框架中使用了两种代理方式: 1.JDK自带的动态代理. 2.Spring框架自己提供的CGLIB的方式. 这两种也是Spring框架核心AOP的基础. 在详细讲解上述提到的动态代理和CG ...

  4. Spring中AOP原理,源码学习笔记

    一.AOP(面向切面编程):通过预编译和运行期动态代理的方式在不改变代码的情况下给程序动态的添加一些功能.利用AOP可以对应用程序的各个部分进行隔离,在Spring中AOP主要用来分离业务逻辑和系统级 ...

  5. Spring中AOP简介与切面编程的使用

    Spring中AOP简介与使用 什么是AOP? Aspect Oriented Programming(AOP),多译作 "面向切面编程",也就是说,对一段程序,从侧面插入,进行操 ...

  6. 框架源码系列十:Spring AOP(AOP的核心概念回顾、Spring中AOP的用法、Spring AOP 源码学习)

    一.AOP的核心概念回顾 https://docs.spring.io/spring/docs/5.1.3.RELEASE/spring-framework-reference/core.html#a ...

  7. Spring 中aop切面注解实现

    spring中aop的注解实现方式简单实例   上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们 ...

  8. Spring中AOP相关源码解析

    前言 在Spring中AOP是我们使用的非常频繁的一个特性.通过AOP我们可以补足一些面向对象编程中不足或难以实现的部分. AOP 前置理论 首先在学习源码之前我们需要了解关于AOP的相关概念如切点切 ...

  9. AOP 与 Spring中AOP使用(上)

    AOP简介 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程, 通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术. AOP是OOP的延续 ...

随机推荐

  1. WIndowsServer ---------- 将本地文件映射到服务器

    我们在进行在文件中传递文件的时候,对于一些文件比较大的话就很难传递成功,所以可以同过文件映射, 将需要的文件所在的盘符映射到服务器中,在服务其中进行文件传递. 1.找到电脑中的远程桌面,在附件或控制面 ...

  2. java -- eclipse运行javaweb 项目

    这个是和上一个放在一块的 创建javaweb项目,要是想要创建maven项目,java项目都可以,我要和tomcat放在一块所以 就创建javaweb项目 创建项目起一个有意义的项目名    选择一个 ...

  3. 小程序接口无法传递session校验验证码

    今天在写接口的时候发现一个问题,我用apiaaz测试一切正常,但是从小程序接口请求验证码,一直验证失败. 最开始用的图形验证码,查阅了不少资料,最后怀疑是cookie的问题,解决无果,换成了短信验证码 ...

  4. 62 网络编程(三)——UDP编程

    UDP编程标准步骤 服务器端 使用DatagramSocket创建服务端:DatagramSocket server = new DatagramSocket(port);//参数为自定义端口号 准备 ...

  5. Go在windows下执行命令行指令

    需要在Go写的服务里面调用命令行或者批处理,并根据返回的结果做处理. 在网上搜索了一翻,验证成功,现记录如下: cmd := exec.Command("cmd") // cmd ...

  6. 百度前端技术学院task16源代码

    欢迎访问我的github:huanshen 做这道题目的时候遇到了很多困难. 1.怎么给空对象添加数据,愣是不知道从哪里下手:遍历对象,一个个输出操作: 2.中英文的正则表达式不知道,赶紧去百度: 3 ...

  7. 【题解】Largest Rectangle in a Histogram [SP1805] [POJ2559]

    [题解]Largest Rectangle in a Histogram [SP1805] [POJ2559] [题目描述] 传送: \(Largest\) \(Rectangle\) \(in\) ...

  8. MyBatis系列(二) MyBatis接口绑定与多参数传递

    前言 通过上一篇博文的,已经可以做到通过MyBatis连接数据库,现在再来介绍一种方法通过接口绑定SQL语句. 不使用接口绑定的方式 不使用接口绑定的方式,是通过调用SqlSession中的selec ...

  9. arguments 使用

    function test(){ var paramsNum = arguments.length; var sum = 0; for(var i = 0;i<paramsNum;i++){ c ...

  10. 面对代码中过多的if...else的解决方法

    原 6个实例详解如何把if-else代码重构成高质量代码 置顶 2017年09月11日 23:47:12 yinnnnnnn 阅读数 21433更多 分类专栏: # 理论   版权声明:本文为博主原创 ...