项目场景:
多数据源需求:
需要使用多数据源,或者某方法需要调用其它数据库or同库其它schema的情况
解决方法
1.在pom.xml中引入依赖
<!--引入依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
2.配置数据源,master、other-schema为两个不同数据源所对应的配置
spring:
datasource:
dynamic:
primary: master
datasource:
master:
udriver-class-name: org.postgresql.Driver
url: jdbc:postgresql://ip:port/database?currentSchema=schema
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
other_schema:
udriver-class-name: org.postgresql.Driver
url: jdbc:postgresql://ip:port/database?currentSchema=otherschema
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
3.用注解@DS(“上一步配置的数据源名”)进行动态数据源切换
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.stereotype.Service;
@Service
public class xxxxxServiceOrMapper {
//此处切换为other_schema数据源,方法内将使用other_schema数据源
@DS("other_schema")
public xxxx getxxxxx() {
return xxxxxMapper.getxxxxx(null);
}
}