Springboot创建多数据源

yml文件
yml 复制代码
spring:
  datasource:
    dynamic:
      # 设置默认的数据源或者数据源组,默认值即为 master
      primary: master
      datasource:
        # 主库数据源
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&autoReconnect=true
          username: root
          password: xxxxx
        # 本地库数据源
        local:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&autoReconnect=true
          username: root
          password: xxxxx
        #Doris数据源
        doris:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://xxx.xxx.xxx.xxx:9030/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&nuLlCatalogMeansCurrent=true
          username: root
          password: xxxxx
 # ...

这里省略了其他的配置信息,多数据源的配置关注这些内容即可.

构建每个数据对应的注解
java 复制代码
// 主数据源,@DS中填入yml文件中已经配置的数据源的名称即可
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@DS("master")
public @interface MysqlMaster {
}

// 本地数据源,@DS中填入yml文件中已经配置的数据源的名称即可
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@DS("master")
public @interface MysqlLocal {
}

// Doris数据源,@DS中填入yml文件中已经配置的数据源的名称即可
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@DS("doris")
public @interface Doris {
}
在Mapper中引入注解
java 复制代码
@Mapper
@MysqlMaster
public interface MasterMapper extends BaseMapper {
    User1 selectAll();
    // ...
}

@Mapper
@MysqlLocal
public interface LocalMapper extends BaseMapper {
    User2 selectAll();
    // ...
}

@Mapper
@Doris
public interface DorisMapper extends BaseMapper {
    User3 selectAll();
    // ...
}

多数据源的配置及使用到这里就结束了.

相关推荐
R-sz3 分钟前
java流式计算 获取全量树形数据,非懒加载树,递归找儿
java·开发语言·windows
Ramos丶8 分钟前
【ABAP】 从无到有 新建一个Webdynpro程序
java·前端·javascript
sniper_fandc19 分钟前
SpringMVC详解
java·springmvc
TT哇2 小时前
【Java EE初阶】计算机是如何⼯作的
java·redis·java-ee
paopaokaka_luck2 小时前
基于SpringBoot+Vue的电影售票系统(协同过滤算法)
vue.js·spring boot·后端
陌殇殇5 小时前
SpringBoot整合SpringCache缓存
spring boot·redis·缓存
小林学习编程7 小时前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
ladymorgana8 小时前
【Spring boot】tomcat Jetty Undertow对比,以及应用场景
spring boot·tomcat·jetty
IT_10248 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
Fireworkitte8 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel