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();
    // ...
}

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

相关推荐
LUCIAZZZ11 分钟前
HikariCP数据库连接池原理解析
java·jvm·数据库·spring·springboot·线程池·连接池
考虑考虑20 分钟前
Springboot3.5.x结构化日志新属性
spring boot·后端·spring
sky_ph34 分钟前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
TTDreamTT41 分钟前
SpringBoot十二、SpringBoot系列web篇之过滤器Filte详解
spring boot
IDRSolutions_CN1 小时前
PDF 转 HTML5 —— HTML5 填充图形不支持 Even-Odd 奇偶规则?(第二部分)
java·经验分享·pdf·软件工程·团队开发
hello早上好1 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
HelloWord~2 小时前
SpringSecurity+vue通用权限系统2
java·vue.js
让我上个超影吧2 小时前
黑马点评【基于redis实现共享session登录】
java·redis
BillKu3 小时前
Java + Spring Boot + Mybatis 插入数据后,获取自增 id 的方法
java·tomcat·mybatis
全栈凯哥3 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表