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;
    }

}

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

相关推荐
mldong2 分钟前
从 mldong 到 jeeflow:一个工作流引擎的独立进化
后端
The Chosen One98519 分钟前
高进度算法模板速记(待完善)
java·前端·算法
陈随易24 分钟前
MoonBit抓包模块pcap,查看电脑的每一次联网通信
前端·后端·程序员
Aaron - Wistron1 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境1 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境1 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
极光代码工作室2 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
IT_陈寒3 小时前
Vite热更新失效?你可能漏了这个配置
前端·人工智能·后端
Leighteen3 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言