作者:kas8288408 | 来源:互联网 | 2023-09-15 14:14
链接: MyBatis-Plus推荐的多数据源.
链接: 一个基于springboot的快速集成多数据源的启动器.
链接: 多数据源.
链接: 多数据源.
链接: dynamic-datasource文档.
dynamic-datasource-spring-boot-starter
是一个基于springboot的快速集成多数据源的启动器,主要用于读写分离,一主多从的环境,纯多库都行
如果你的项目比较复杂,建议使用 sharding-jdbc
导入依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>dynamic-datasource-spring-boot-starterartifactId>
<version>${version}version>
dependency>
配置yml
spring:
datasource:
druid:
filters: stat,wall
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
use-global-data-source-stat: true
stat-view-servlet:
login-username:
login-password:
enabled: true
dynamic:
primary: master
strict: false
datasource:
master:
url:
username: xxx
password: xxx
driver-class-name: oracle.jdbc.OracleDriver
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
validation-query: select 1 from dual
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
slave_1:
url:
username: xxx
password: xxx
driver-class-name: oracle.jdbc.OracleDriver
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
引入druid的注意
排除 原生Druid的快速配置类
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
为什么要排除DruidDataSourceAutoConfigure
DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找url,username,password等。而我们动态数据源的配置路径是变化的。
使用 @DS 切换数据源
@DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解,强烈建议注解在mapper接口方法上。
@DS("master")
public interface UserMapper {
@Select("SELECT * FROM user")
@DS
List<User> selectAll();
}