Springboot项目多数据源配置详细步骤

一、引入对应的依赖

复制代码
<!--    Oracel    -->
<dependency>
  <groupId>com.oracle.database.jdbc</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>11.2.0.4</version>
</dependency>
<!--for SqlServer-->
<dependency>
  <groupId>com.microsoft.sqlserver</groupId>
  <artifactId>mssql-jdbc</artifactId>
  <version>8.2.0.jre8</version>
</dependency>
<!--其他类型,引入对应的数据源即可-->

二、配置文件配置

复制代码
spring:
  cloud:
    nacos:
      config:
        enabled: true
        server-addr: xx.xxx.xxx.88:8848
        file-extension: yml
      discovery:
        enabled: true
        server-addr: 10.254.253.88:8848
  #动态配置
  datasource:
    dynamic:
      primary: master
      datasource:
        #oracle
        master:
          url: jdbc:oracle:thin:@xx.xxx.xxx.xx:1521:ORCL
          driver-class-name: oracle.jdbc.driver.OracleDriver
          username: xxx
          password: xxxx@xxxxx.xxx.cn
          #SQLServer
        person:
          driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
          url: jdbc:sqlserver://xx.xxx.xxx.xx:1433;DatabaseName=TransDbCpu
          username: xxxx
          password: xxxx!xxx
          #oracle
        jwPerson:
          url: jdbc:oracle:thin:@xx.xxx.xxx.xx:1521:ORCL
          driver-class-name: oracle.jdbc.driver.OracleDriver
          username: xx
          password: xxxxxxx@xxxxx.xxx.cn

三、代码中使用

举一个oracle的例子,其他类似,在实现类中增加@DS注释,注意一个实现类只可使用一种

复制代码
package com.base.info.service.impl;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.base.info.dao.DepartDao;
import com.base.info.dao.JWPersonDao;
import com.base.info.dao.PersonDao;
import com.base.info.model.entity.SchoolJWPersonEntity;
import com.base.info.model.entity.SchoolPersonEntity;
import com.base.info.model.qo.PersonInfoQo;
import com.base.info.service.SynJWPersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author wcg
 * @since 2024/01/31
 */
@Slf4j
@Service
@DS("jwPerson")   //要与配置中的一致
public class SynJWPersonServiceImpl implements SynJWPersonService {

    @Resource
    private JWPersonDao jwPersonDao; //对应的dao层及实体类是对应数据库的表

    @Override
    public List<String> schoolPersonList(PersonInfoQo personInfoQo) {
        return null;
    }

}

四、工作中使用到了,特此做个记录,使用很顺畅,有问题可以留言讨论。

相关推荐
海边的Kurisu1 小时前
苍穹外卖日记 | Day1 苍穹外卖概述、开发环境搭建、接口文档
java
uzong3 小时前
后端线上发布计划模板
后端
C雨后彩虹4 小时前
任务最优调度
java·数据结构·算法·华为·面试
uzong4 小时前
软件工程师应该关注的几种 UML 图
后端
heartbeat..4 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X5 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
上进小菜猪6 小时前
基于 YOLOv8 的 100 类中药材智能识别实战 [目标检测完整源码]
后端
元Y亨H6 小时前
Nacos - 服务发现
java·微服务
微露清风7 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
dasi02277 小时前
Java趣闻
java