一、实现思路

在yml中定义多个数据源的配置,然后创建一个类DynamicDataSource去继承AbstractRoutingDataSource类

AbstractRoutingDataSource类中

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;
}

该方法用来得到当前数据源:

1:调用了determineCurrentLookupKey()方法来得到lookupKey(重写该方法决定我们的lookupKey的从哪里获取)

2:再通过lookupKey从resolvedDataSources得到DataSource,如果获取不到则取默认数据源

@Override
public void afterPropertiesSet() {
if (this.targetDataSources == null) {
throw new IllegalArgumentException("Property 'targetDataSources' is required");
}
this.resolvedDataSources = new HashMap<>(this.targetDataSources.size());
this.targetDataSources.forEach((key, value) -> {
Object lookupKey = resolveSpecifiedLookupKey(key);
DataSource dataSource = resolveSpecifiedDataSource(value);
this.resolvedDataSources.put(lookupKey, dataSource);
});
if (this.defaultTargetDataSource != null) {
this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
}
}

3:resolvedDataSources其实是通过该类的targetDataSources得到

实现思路:

1、在yml中配置多个数据源的参数

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.1.131/springbootDemo?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
#Oracle需要打开注释
#validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: true
url-pattern: /druid/*
#login-username: admin
#login-password: admin
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true #多数据源的配置
dynamic:
datasource:
slave1:
url: jdbc:mysql://192.168.1.131/springbootDemo?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
slave2:
url: jdbc:mysql://192.168.1.131/spring_data_jpa?characterEncoding=utf-8&useSSL=false
username: root
password: 123456

2、将yml中的多个配置加载进map,name做key, value就是配置属性对象

/**
* 将yml中的配置加载进DataSourceProperties并存入map
*
*/
@ConfigurationProperties(prefix="dynamic")
@Data
public class DynamicDataSourceProperties {
public HashMap<String,DataSourceProperties> dataSource=new HashMap<String,DataSourceProperties>();
}
package com.ganlong.dataSource.properties;

import lombok.Data;

@Data
public class DataSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password; /**
* Druid默认参数
*/
private int initialSize = 2;
private int maxActive = 10;
private int minIdle = -1;
private long maxWait = 60 * 1000L;
private long timeBetweenEvictionRunsMillis = 60 * 1000L;
private long minEvictableIdleTimeMillis = 1000L * 60L * 30L;
private long maxEvictableIdleTimeMillis = 1000L * 60L * 60L * 7;
private String validationQuery = "select 1";
private int validationQueryTimeout = -1;
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
private boolean testWhileIdle = true;
private boolean poolPreparedStatements = false;
private int maxOpenPreparedStatements = -1;
private boolean sharePreparedStatements = false;
private String filters = "stat,wall";
}

3、用加载好的propertiesMap创建出多个DruidDataSource ,并setTargetDataSources


@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig { @Autowired
private DynamicDataSourceProperties dynamicDataSourceProperties; @Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
} @Bean
public DynamicDataSource dynamicDataSource(DataSourceProperties dataSourceProperties) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 设置默认数据源
DruidDataSource defaultDataSource=DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
dynamicDataSource.setDefaultTargetDataSource(defaultDataSource); // 设置多数据源
dynamicDataSource.setTargetDataSources(targetDataSources());
return dynamicDataSource;
} @Bean
public Map<Object,Object> targetDataSources(){
// 循环设置targetDataSources
HashMap<String, DataSourceProperties>dataSourcePropertiesMap = dynamicDataSourceProperties.getDataSource();
Map<Object, Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
dataSourcePropertiesMap.forEach((k, v) -> {
DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v);
targetDataSources.put(k, druidDataSource);
});
return targetDataSources;
}
}
package com.ganlong.dataSource.config;

import java.sql.SQLException;

import com.alibaba.druid.pool.DruidDataSource;
import com.ganlong.dataSource.properties.DataSourceProperties; /**
* 根据properties创建DruidDataSource
* @author yl
*
*/
public class DynamicDataSourceFactory { public static DruidDataSource buildDruidDataSource(DataSourceProperties properties) {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(properties.getDriverClassName());
druidDataSource.setUrl(properties.getUrl());
druidDataSource.setUsername(properties.getUsername());
druidDataSource.setPassword(properties.getPassword()); druidDataSource.setInitialSize(properties.getInitialSize());
druidDataSource.setMaxActive(properties.getMaxActive());
druidDataSource.setMinIdle(properties.getMinIdle());
druidDataSource.setMaxWait(properties.getMaxWait());
druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
druidDataSource.setMaxEvictableIdleTimeMillis(properties.getMaxEvictableIdleTimeMillis());
druidDataSource.setValidationQuery(properties.getValidationQuery());
druidDataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout());
druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
druidDataSource.setTestOnReturn(properties.isTestOnReturn());
druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
druidDataSource.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements());
druidDataSource.setSharePreparedStatements(properties.isSharePreparedStatements()); try {
druidDataSource.setFilters(properties.getFilters());
druidDataSource.init();
} catch (SQLException e) {
e.printStackTrace();
}
return druidDataSource;
}
}

4、用aop和注解去设置lookupKey

@Component
public class ThreadlocalHolder { public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>(); public void set(String dataSource) {
threadLocal.set(dataSource);
} public String get() {
return threadLocal.get();
} public void removeAll() {
threadLocal.remove();
}
}
package com.ganlong.dataSource.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource{ @Autowired
private ThreadlocalHolder threadlocalHolder; @Override
protected Object determineCurrentLookupKey() {
return threadlocalHolder.get();
}
}

LookupKey用ThreadLocal来存取。(ThreadLocal主要是避免线程安全问题,如果多个方法之间需要同一个参数,我们声明成 成员变量的话会存在线程安全问题,声明成局部变量然后通过形参去传递,又过于麻烦,这时就可以考虑用ThreadLocal来传递)

package com.ganlong.dataSource.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource {
String value() default "";
}
package com.ganlong.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import com.ganlong.dataSource.annotation.DataSource;
import com.ganlong.dataSource.config.ThreadlocalHolder; @Component
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DataSourceAspect { @Autowired
private ThreadlocalHolder threadLocal; @Pointcut("@annotation(com.ganlong.dataSource.annotation.DataSource) || @within(com.ganlong.dataSource.annotation.DataSource)")
public void dataSourcePointCut() { } @Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
// 得到方法上的注解
MethodSignature signature =(MethodSignature)point.getSignature();
Method method =signature.getMethod();
DataSource methodDataSource = method.getAnnotation(DataSource.class); // 得到类上的注解
Class targetClass = point.getTarget().getClass();
DataSource targetClassDataSource = (DataSource) targetClass.getAnnotation(DataSource.class); if(methodDataSource!=null || targetClassDataSource!=null) {
String dataSourceName="";
if(methodDataSource!=null) {
dataSourceName = methodDataSource.value();
}else {
dataSourceName = targetClassDataSource.value();
}
//存入threadlocal
threadLocal.set(dataSourceName);
}
try {
return point.proceed();
}finally {
// 最后清空当前线程的数据源
threadLocal.removeAll();
}
}
}

切面类记得加上@Order(Ordered.HIGHEST_PRECEDENCE),让该切面在最优先级这样才会起作用。

还有如果开启了事务那么就不能再切换数据源了(切换也会失效),一个事务只能对应一个数据源(最早的那个数据源)

springboot 多数据源(aop方式)的更多相关文章

  1. springboot 双数据源+aop动态切换

    # springboot-double-dataspringboot-double-data 应用场景 项目需要同时连接两个不同的数据库A, B,并且它们都为主从架构,一台写库,多台读库. 多数据源 ...

  2. Springboot+Mybatis+Pagehelper+Aop动态配置Oracle、Mysql数据源

      本文链接:https://blog.csdn.net/wjy511295494/article/details/78825890 Springboot+Mybatis+Pagehelper+Aop ...

  3. SpringBoot整合Mybatis多数据源 (AOP+注解)

    SpringBoot整合Mybatis多数据源 (AOP+注解) 1.pom.xml文件(开发用的JDK 10) <?xml version="1.0" encoding=& ...

  4. Spring中AOP方式实现多数据源切换

    作者:suroot spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性.而这样的方案就会不同于常见的单一数据实例的方案,这就要 ...

  5. 基于springboot通过注解AOP动态切换druid多数据源--mybatis

    控制于接口之上: 开始:demo地址  在lsr-core-base中 自定义注解: /** * @Description: 数据源切换注解 * @Package: lsr-microservice ...

  6. SpringBoot多数据源动态切换数据源

    1.配置多数据源 spring: datasource: master: password: erp_test@abc url: jdbc:mysql://127.0.0.1:3306/M201911 ...

  7. 搞定SpringBoot多数据源(2):动态数据源

    目录 1. 引言 2. 动态数据源流程说明 3. 实现动态数据源 3.1 说明及数据源配置 3.1.1 包结构说明 3.1.2 数据库连接信息配置 3.1.3 数据源配置 3.2 动态数据源设置 3. ...

  8. SpringBoot多数据源:动态数据源

    目录 1. 引言 2. 动态数据源流程说明 3. 实现动态数据源 3.1 说明及数据源配置 3.1.1 包结构说明 3.1.2 数据库连接信息配置 3.1.3 数据源配置 3.2 动态数据源设置 3. ...

  9. SpringBoot多数据源以及事务处理

    背景 在高并发的项目中,单数据库已无法承载大数据量的访问,因此需要使用多个数据库进行对数据的读写分离,此外就是在微服化的今天,我们在项目中可能采用各种不同存储,因此也需要连接不同的数据库,居于这样的背 ...

  10. Springboot中使用AOP统一处理Web请求日志

    title: Springboot中使用AOP统一处理Web请求日志 date: 2017-04-26 16:30:48 tags: ['Spring Boot','AOP'] categories: ...

随机推荐

  1. kotlin更多语言结构——>类型安全的构建器

    通过使用命名得当的函数作为构建器,结合带有接收者的函数字面值,可以在 Kotlin 中创建类型安全.静态类型 的构建器 类型安全的构建器可以创建基于 Kotlin 的适用于采用半声明方式构建复杂层次数 ...

  2. 如何在 ubuntu 上搭建 minio

    由于腾讯的对象存储服务器(COS)的半年免费试用期已过,所以寻思鼓捣一下 minio,试着在自己的服务器上搭建一套开源的 minio 对象存储系统. 单机部署基本上有以下两种方式. 直接安装 最基础的 ...

  3. centos下搭建php开发环境(lamp)

    由于个人非常喜欢爱linux系开发php项目. 因为某些原因,经常需要手动搭建环境 经常在网上找到的教程经常不太一样 虽然最终都能完成搭建,但是总是觉得不太爽 还不如自己写一篇,需要的时候肯定能找到 ...

  4. Python实现火柴人的设计与实现

    1.引言 火柴人(Stick Figure)是一种极简风格的图形,通常由简单的线段和圆圈组成,却能生动地表达人物的姿态和动作.火柴人不仅广泛应用于动画.漫画和涂鸦中,还可以作为图形学.人工智能等领域的 ...

  5. .NET 实现的零部件离散型 MES+WMS 系统

    前言 随着制造业的不断发展,企业对于生产效率和管理水平的要求越来越高. EasyMES 是一款基于 .NET 6 开发的零部件离散型 MES(Manufacturing Execution Syste ...

  6. (系列十)Vue3中菜单和路由的结合使用,实现菜单的动态切换(附源码)

    说明 该文章是属于OverallAuth2.0系列文章,每周更新一篇该系列文章(从0到1完成系统开发). 该系统文章,我会尽量说的非常详细,做到不管新手.老手都能看懂. 说明:OverallAuth2 ...

  7. MYSQL SQL做题总结

    一.关于join 1.内外左右连接 2.交叉联结(corss join) 使用交叉联结会将两个表中所有的数据两两组合.如下图,是对表"text"自身进行交叉联结的结果: 3.三表双 ...

  8. 3-4 C++迭代器初步

    目录 3.4.0 为什么要有迭代器 3.4.1使用迭代器 迭代器的比较操作 用迭代器写一个遍历 取出迭代器中的元素:解引用 * 迭代器的类型 使用迭代器时的注意点 3.4.2 迭代器的算术操作 常见操 ...

  9. vue通过ollama接口调用开源模型

    先展示下最终效果: 第一步:先安装ollama,并配置对应的开源大模型. 安装步骤可以查看上一篇博客: ollama搭建本地ai大模型并应用调用  第二步:需要注意两个配置,页面才可以调用 1)OLL ...

  10. 【一步步开发AI运动小程序】十八、如何识别用户上传图片中的人体、运动、动作、姿态?

    [云智AI运动识别小程序插件],可以为您的小程序,赋于人体检测识别.运动检测识别.姿态识别检测AI能力.本地原生识别引擎,内置10余个运动,无需依赖任何后台或第三方服务,有着识别速度快.体验佳.扩展性 ...