作者: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. ThinkPHP5 使用 JWT 进行加密

    使用 Github 的 firebase\JWT - 使用 Composer 安装此扩展 - 代码示例 <?php /** * [InterCommon-接口公用] * @Author Rain ...

  2. [转帖]美团在Redis上踩过的一些坑-3.redis内存占用飙升

    美团在Redis上踩过的一些坑-3.redis内存占用飙升 博客分类: 运维 redis redismonitor内存突增client listinfo     转载请注明出处哈:http://car ...

  3. Java学习:抽象方法和抽象类的使用

    抽象 抽象方法:就是加上abstract关键字,然后去掉大括,直接分号结束.抽象类:抽象方法所在的类,必须是抽象类才行.在class之前写上abstract即可. 如何使用抽象类和抽象方法: 1.不能 ...

  4. linux中常用命令alias

    1.查看系统中所有的命令别名 alias 2.查看指定的别名 alias 别名 2.设定别名 alias 别名='原命令' 3.删除别名 unalias 别名 4.使别名永久生效 vi ~/.bash ...

  5. Mysql系列(六)—— MySQL索引介绍

    前言 索引种类 索引维护 如何使用索引 一.索引索引种类 MySQL中索引主要包含以下几种: 普通索引 唯一索引 主键索引 联合索引 全文索引 二.索引维护 在简述了索引的类型后,再来了解下如何维护索 ...

  6. kubenetes之配置pod的QoS

    系列目录 上节提到过,QoS影响pod的调度和驱离,本节讲解如何通过配置pod来使它自动被赋予一个QoS 实际上是pod的配置达到一定标准,则kubernetes会自动为其它添加一个QoS类 QoS类 ...

  7. List/Map 导出到表格(使用注解和反射)

    Java 的 POI 库可以用来创建和操作 Excel 表格,有时候我们只需要简单地将 List 或 Map 导出到表格,样板代码比较多,不够优雅.如果能像 Gson 那样,使用注解标记要导出的属性, ...

  8. java中什么是抽象类(abstract)

    一.什么是抽象类 由abstract修饰的方法叫抽象方法:由abstract修饰的类叫抽象类.抽象的类无法进行实例化,因为他不是具体存在的类,或者说这样的类还不够完善,不能直接使用new关键字调用其构 ...

  9. Unable to connect to HBase using Phoenix JDBC Driver

    Feb 01, 2017; 5:21pm Unable to connect to HBase using Phoenix JDBC Driver 9 posts Hi All,   I am try ...

  10. windows7下安装msys2

    系统: windows 7 首先需要msys2的安装包,可以去官网下载安装包官网地址: http://www.msys2.org/本次下载的是 msys2-x86_64-20190524.exe 注意 ...