使⽤dynamic-datasource-spring-boot-starter配置多数据源1、依赖
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
5.1.48
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: sql.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: sql.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、使⽤
springframework依赖@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();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。