springboot多数据源<一>
平时切换数据源总能想到,利用注解,切面,反射结合 AbstractRoutingDataSource进行切换 springboot的装配很容易被大家忽略 下面我介绍下一种多数据源切换的方式,到Dao层利用 import com.baomidou.dynamic.datasource.annotation.DS注解注入数据源的方式使用不同的数据库。 @Mapper @DS("user") public interface UserMapper @Mapper @DS("admin") public interface AdminMpper
使用时直接在服务接口层进行注入即可
<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.0.0</version> </dependency>
配置样例: spring.datasource.dynamic.primary=local #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源 spring.datasource.dynamic.strict=false spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.dynamic.datasource.master.username=root spring.datasource.dynamic.datasource.master.url=jdbc:mysql://127.0.0.1:3306/quanxian?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.dynamic.datasource.master.password= spring.datasource.dynamic.datasource.master.hikari.min-idle=5 spring.datasource.dynamic.datasource.master.hikari.idle-timeout=180000 spring.datasource.dynamic.datasource.master.hikari.max-pool-size= 10 spring.datasource.dynamic.datasource.master.hikari.is-auto-commit=true spring.datasource.dynamic.datasource.master.hikari.pool-name= myHikaricp2 spring.datasource.dynamic.datasource.master.hikari.max-lifetime=180000 spring.datasource.dynamic.datasource.master.hikari.connection-timeout=300000 spring.datasource.dynamic.datasource.master.hikari.connection-test-query= select 1 spring.datasource.dynamic.datasource.master.hikari.validation-timeout= 500 spring.datasource.dynamic.datasource.local.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.dynamic.datasource.local.username=root spring.datasource.dynamic.datasource.local.url=jdbc:mysql://127.0.0.1:3306/quanxian?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.dynamic.datasource.local.password= spring.datasource.dynamic.datasource.local.hikari.min-idle=5 spring.datasource.dynamic.datasource.local.hikari.idle-timeout=180000 spring.datasource.dynamic.datasource.local.hikari.max-pool-size= 10 spring.datasource.dynamic.datasource.local.hikari.is-auto-commit=true spring.datasource.dynamic.datasource.local.hikari.pool-name= myHikaricp3 spring.datasource.dynamic.datasource.local.hikari.max-lifetime=180000 spring.datasource.dynamic.datasource.local.hikari.connection-timeout=300000 spring.datasource.dynamic.datasource.local.hikari.connection-test-query= select 1 spring.datasource.dynamic.datasource.local.hikari.validation-timeout= 500
这就完了?是的就是那么简单
很简单不需要我们再写注解反射什么的: 官网:https://www.kancloud.cn/tracy5546/dynamic-datasource/2395791 but是个收费的,下一篇我来写个免费的案例供大家借鉴
一点点学习,一丝丝进步。不懈怠,才不会被时代淘汰