1、依赖
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
5.1.48
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.1
com.baomidou
dynamic-datasource-spring-boot-starter
2.5.7
org.springframework.boot
spring-boot-actuator
2、yml文件配置
spring:
datasource:
# dynamic-datasource-spring-boot-starter 动态数据源的配置内容
dynamic:
primary: users # 设置默认的数据源或者数据源组,默认值即为 master
datasource:
# 订单 orders 数据源配置
orders:
url: jdbc:mysql://127.0.0.1:3306/test_orders?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
# 用户 users 数据源配置
users:
url: jdbc:mysql://127.0.0.1:3306/test_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
3、DBConstants
public class DBConstants {
/**
* 数据源分组 - 订单库
*/
public static final String DATASOURCE_ORDERS = "orders";
/**
* 数据源分组 - 用户库
*/
public static final String DATASOURCE_USERS = "users";
}
4、使用
@Transactional
@DS(DBConstants.DATASOURCE_USERS)
public void method042() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
@Transactional
@DS(DBConstants.DATASOURCE_ORDERS)
public void method05() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
self().method052();
}