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

一、引入对应的依赖



  com.oracle.database.jdbc
  ojdbc6
  11.2.0.4



  com.microsoft.sqlserver
  mssql-jdbc
  8.2.0.jre8

二、配置文件配置

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: [email protected]
          #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: [email protected]

三、代码中使用

举一个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 schoolPersonList(PersonInfoQo personInfoQo) {
        return null;
    }

}

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

你可能感兴趣的:(spring,boot,后端,java)