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

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

相关推荐
Tigshop开源商城1 小时前
『订单税率+收货地址校验国家字段』功能上新|跨境运营更高效,Tigshop开源商城系统 JAVA v5.8.23 版本更新
java·开源商城系统·tigshop
REDcker1 小时前
C++变量存储与ELF段布局详解 从const全局到rodata与nm_readelf验证实践
java·c++·面试
kobesdu3 小时前
【ROS2实战笔记-19】ROS2 生命周期节点的启动顺序、状态转换陷阱与热备方案
java·前端·笔记·机器人·ros·ros2
neo_Ggx233 小时前
Maven 版本管理详解:SNAPSHOT、Release 与 Nexus 仓库的区别和影响
java·maven
matlabgoodboy3 小时前
软件开发定制小程序APP帮代做java代码代编写C语言设计python编程
java·c语言·小程序
江离w3 小时前
新版vibecoding项目初始化指令
java
tongluowan0074 小时前
Spring MVC 底层工作流程+源码分析
java·spring·mvc
java1234_小锋4 小时前
SpringBoot为什么要禁止循环依赖?
java·数据库·spring boot
折哥的程序人生 · 物流技术专研5 小时前
《Java 100 天进阶之路》第17篇:Java常用包装类与自动装箱拆箱深入
java·开发语言·后端·面试
RH2312115 小时前
2026.5.12 Linux
java·linux·数据结构