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

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

相关推荐
Themberfue9 分钟前
基础算法之双指针--Java实现(下)--LeetCode题解:有效三角形的个数-查找总价格为目标值的两个商品-三数之和-四数之和
java·开发语言·学习·算法·leetcode·双指针
深山夕照深秋雨mo17 分钟前
在Java中操作Redis
java·开发语言·redis
小小娥子19 分钟前
【Redis】Hash类型的常用命令
数据库·spring boot·redis
努力的布布23 分钟前
SpringMVC源码-AbstractHandlerMethodMapping处理器映射器将@Controller修饰类方法存储到处理器映射器
java·后端·spring
xujinwei_gingko23 分钟前
Spring MVC 常用注解
java·spring·mvc
PacosonSWJTU28 分钟前
spring揭秘25-springmvc03-其他组件(文件上传+拦截器+处理器适配器+异常统一处理)
java·后端·springmvc
PacosonSWJTU30 分钟前
spring揭秘26-springmvc06-springmvc注解驱动的web应用
java·spring·springmvc
原野心存1 小时前
java基础进阶——继承、多态、异常捕获(2)
java·java基础知识·java代码审计
进阶的架构师1 小时前
互联网Java工程师面试题及答案整理(2024年最新版)
java·开发语言
黄俊懿1 小时前
【深入理解SpringCloud微服务】手写实现各种限流算法——固定时间窗、滑动时间窗、令牌桶算法、漏桶算法
java·后端·算法·spring cloud·微服务·架构