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

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

相关推荐
乌萨奇也要立志学C++5 小时前
【Linux】Ext系列文件系统 从磁盘结构到文件存储的原理剖析
android·linux·缓存·1024程序员节
Boop_wu5 小时前
[MySQL] 数据库设计
java·数据库·oracle
墨白曦煜5 小时前
Java集合框架整体分类(完整的集合框架关系)
java·开发语言
后端小张5 小时前
【JAVA 进阶】SpringBoot集成Sa-Token权限校验框架深度解析
java·spring boot·spring·架构·sa-token·springboot·权限框架
想ai抽5 小时前
Flink中的Lookup join和Temporal join 的语法是一样的吗?
java·大数据·flink
小白学大数据5 小时前
Java爬虫性能优化:以喜马拉雅音频元数据抓取为例
java·爬虫·性能优化
熬了夜的程序员6 小时前
【LeetCode】80. 删除有序数组中的重复项 II
java·数据结构·算法·leetcode·职场和发展·排序算法·动态规划
乐之者v6 小时前
Grafana监控可视化
java·grafana
weixin_419658316 小时前
Spring的三级缓存和SpringMVC的流程
java·spring·缓存
lang201509286 小时前
Spring Boot Actuator应用信息Application Information全解析
spring boot·后端·elasticsearch