Springboot 集成 Dynamic-Datasource 多数据源组件

发布于:2024-01-24 ⋅ 阅读:(71) ⋅ 点赞:(0)

Springboot 集成 Dynamic-Datasource 多数据源组件

1. 来源

生态 | MyBatis-Plus

2. 解决什么问题

纯粹多库 读写分离 一主多从 混合模式。

3. 引入依赖
  1. 引入dynamic-datasource-spring-boot-starter。

spring-boot 1.5.x 2.x.x


<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>${version}</version>
</dependency>

spring-boot3及以上


<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
    <version>${version}</version>
</dependency>
4.添加配置

这里采用的是混合模式

spring:
    datasource:
        dynamic:
            aop:
                enabled: true
            enabled: true #启用动态数据源,默认true
            primary: center#设置默认的数据源或者数据源组,默认值即为master
            grace-destroy: false #是否优雅关闭数据源,默认为false,设置为true时,关闭数据源时如果数据源中还存在活跃连接,至多等待10s后强制关闭
            datasource:
                center:
                    url: jdbc:mysql://xx.xx.xxx.xx/center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useTimezone=true&serverTimezone=Asia/Shanghai
                    username: username
                    password: password
                    driver-class-name: com.mysql.cj.jdbc.Driver
                # ck数据源
                clickhouse:
                    driver-class-name: com.clickhouse.jdbc.ClickHouseDriver
                    url: jdbc:clickhouse://xx.xx.xx.xx/data
                    username: username
                    password: password


5. 代码层面切换数据源
@Service
@DS("center")
public class UserServiceImpl implements UserService {
    
}
6.异常信息

参照: Dynamic-Datasource

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到