springboot+dynamic-datasource多数据源配置动态切换

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
简介: springboot+dynamic-datasource多数据源配置动态切换

官方教程

https://github.com/baomidou/dynamic-datasource-spring-boot-starter
https://www.kancloud.cn/tracy5546/dynamic-datasource/2344619

一、引入依赖

导入数据库驱动,数据库连接池(非必须),数据库操作框架。

      <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
   <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        </dependency>

二、配置文件

# 开发环境配置
spring:
  profiles: dev
  autoconfigure:
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    dynamic:
      druid:
        initial-size: 10
        # 初始化大小,最小,最大
        min-idle: 20
        maxActive: 500
        # 配置获取连接等待超时的时间
        maxWait: 60000
        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        timeBetweenEvictionRunsMillis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        minEvictableIdleTimeMillis: 300000
        testWhileIdle: true
        testOnBorrow: true
        validation-query: SELECT 1
        testOnReturn: false
        # 打开PSCache,并且指定每个连接上PSCache的大小
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall
        filter:
          wall:
            config:
              multi-statement-allow: true
              none-base-statement-allow: true
            enabled: true
        # 配置DruidStatFilter
        web-stat-filter:
          enabled: true
          url-pattern: "/*"
          exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
        # 配置DruidStatViewServlet
        stat-view-servlet:
          enabled: true
          url-pattern: "/druid/*"
          # IP白名单(没有配置或者为空,则允许所有访问)
          allow: #127.0.0.1,192.168.163.1
          # IP黑名单 (存在共同时,deny优先于allow)
          deny: #192.168.1.73
          #  禁用HTML页面上的“Reset All”功能
          reset-enable: false
          # 登录名
          login-username: admin
          # 登录密码
 
          login-password: 111111
        query-timeout: 36000
      primary: master
      strict: false
      datasource:
        master:
          url: jdbc:postgresql://x.xx.xx.xx:5432/x
          username: xxxx
          password: xxxx
          driver-class-name: org.postgresql.Driver
        db1:
          url: jdbc:mysql://x.x.x.x:3306/x?useUnicode=true&characterEncoding=utf-8
          username: xx
          password: xx
          driver-class-name: com.mysql.cj.jdbc.Driver
        db2:
          url: jdbc:mysql://x.x.x.x:3306/x?useUnicode=true&characterEncoding=utf-8
          username: xx
          password: xx
          driver-class-name: com.mysql.cj.jdbc.Driver
        db3:
          url: jdbc:mysql://xx.xx.xx.xx:3306/xx?useUnicode=true&characterEncoding=utf-8
          username: xxx
          password: xxx
          driver-class-name: com.mysql.cj.jdbc.Driver

三、使用

默认使用master数据源,如需切换在调用查询的方法上增加@DS("数据库")

@DS("db1")
 
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class xxxxServiceImpl implements DfsGantryTransactionService {
    @Autowired
    xxxxDao xxxxDao;
 
    @Override
    @DS("db1")
    public Listxxxx> select() {
        return xxxxDao.selectList();
    }
}

四、动态切换

可以根据传入参数(配置文件配置的db1,db2,db3)动态切换数据源

@DS("#dataBaseName")//使用spel从参数获取
public List selectSpelByKey(String dataBaseName) {
  return userMapper.selectUsers();
}

五、加密配置数据库账号密码

import com.baomidou.dynamic.datasource.toolkit.CryptoUtils;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        String password = "123456";
        //使用默认的publicKey ,建议还是使用下面的自定义
        String encodePassword = CryptoUtils.encrypt(password);
        System.out.println(encodePassword);
    }
 
        //自定义publicKey
    public static void main(String[] args) throws Exception {
        String[] arr = CryptoUtils.genKeyPair(512);
        System.out.println("privateKey:  " + arr[0]);
        System.out.println("publicKey:  " + arr[1]);
        System.out.println("url:  " + CryptoUtils.encrypt(arr[0], "jdbc:mysql://127.0.0.1:3306/order"));
        System.out.println("username:  " + CryptoUtils.encrypt(arr[0], "root"));
        System.out.println("password:  " + CryptoUtils.encrypt(arr[0], "123456"));
    }
}

六、手动切换数据源

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
 
@Service
public class UserServiceImpl implements UserService {
 
  @Autowired
  private JdbcTemplate jdbcTemplate;
 
  public List selectAll() {
    DynamicDataSourceContextHolder.push("slave");//手动切换
    return  jdbcTemplate.queryForList("select * from user");
  }
 
}
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
7天前
|
druid Java 关系型数据库
Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
|
3天前
|
缓存 Java 数据库
springboot数据库及缓存常用依赖及配置
springboot数据库及缓存常用依赖及配置
32 9
|
4天前
|
存储 缓存 NoSQL
SpringBoot配置第三方专业缓存框架j2cache
SpringBoot配置第三方专业缓存框架j2cache
14 5
|
1天前
|
NoSQL Java Redis
【源码解析】自动配置的这些细节都不知道,别说你会 springboot
【源码解析】自动配置的这些细节都不知道,别说你会 springboot
|
4天前
|
存储 缓存 NoSQL
SpringBoot配置第三方专业缓存技术Redis
SpringBoot配置第三方专业缓存技术Redis
14 4
|
4天前
|
Java 应用服务中间件 Maven
浅谈后端整合Springboot框架后操作基础配置
浅谈后端整合Springboot框架后操作基础配置
11 3
|
8天前
|
消息中间件 Java Kafka
集成Kafka到Spring Boot项目中的步骤和配置
集成Kafka到Spring Boot项目中的步骤和配置
38 7
|
4天前
|
缓存 监控 NoSQL
SpringBoot配置第三方专业缓存技术jetcache方法缓存方案
SpringBoot配置第三方专业缓存技术jetcache方法缓存方案
15 1
|
4天前
|
存储 缓存 监控
SpringBoot配置第三方专业缓存技术Ehcache
SpringBoot配置第三方专业缓存技术Ehcache
13 1
|
8天前
|
druid Java 关系型数据库
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
72 5