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

}

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

相关推荐
踏浪无痕16 分钟前
SQLInsight:一行依赖,自动追踪API背后的每一条SQL
后端·架构·开源
架构师沉默23 分钟前
一个很多人没想过的问题:为什么编程语言有 for,还要设计 while?
java·后端·架构
Mars酱23 分钟前
1分钟了解响应式编程 | 基本概念
java·后端·rxjava
几颗流星28 分钟前
Rust 像素级绘图入门:Pixels 库核心机制解析
后端·rust
乌日尼乐34 分钟前
【Java基础整理】封装、继承、抽象、接口和多态
java·后端
heartbeat..35 分钟前
JavaWeb 入门 - HttpServletResponse 响应对象 详解
java·网络·http·web·response
zs宝来了37 分钟前
Spring Boot启动流程源码深度解析:电商订单系统面试实战
java·spring boot·面试·源码分析·电商
智航GIS37 分钟前
9.1 多线程入门
java·开发语言·python
我是谁的程序员38 分钟前
不用 Instruments 而在 Windows 环境下测试 iOS App
后端
ServBay38 分钟前
PHP 8.6 新特性预览,更简洁的语法与更严谨的类型控制
后端·php