使用baomidou的DynamicDataSource实现多数据源
1.引入jar包
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
2.核心配置文件application.yml中进行数据源的配置:
bash
spring:
datasource:
dynamic:
#设置默认的数据源或者数据源组,默认值即为master
primary: master
#严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
strict: false
datasource:
master:
url: jdbc:mysql://127.0.0.1:3306/datasource1?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
username: root
password: root
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
driver-class-name: com.mysql.cj.jdbc.Driver
slave_1:
url: jdbc:mysql://127.0.0.1:3306/datasource2?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false
username: root
password: root
initial-size: 1
min-idle: 1
max-active: 20
test-on-borrow: true
driver-class-name: com.mysql.cj.jdbc.Driver
3.使用
@DS可以修饰方法或者类
java
package com.tuling.dynamic.datasource.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.tuling.dynamic.datasource.mapper.FriendMapper;
import com.tuling.dynamic.datasource.entity.Friend;
import com.tuling.dynamic.datasource.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FriendImplService implements FriendService {
@Autowired
FriendMapper friendMapper;
@Override
@DS("slave_1") // 从库, 如果按照下划线命名方式配置多个 , 可以指定前缀即可(组名)
public List<Friend> list() {
return friendMapper.list();
}
@Override
@DS("master")
public void save(Friend friend) {
friendMapper.save(friend);
}
// @DS("master")
// @DSTransactional
// public void saveAll(){
// // 执行多数据源的操作
// }
}