SpringBoot+Dynamic多数据源动态切换
最近做了个小模块,需求就是项目同时读取三个数据库,操作数据。并不是分库分表,只用定时跑,不需要对外提供接口。
技术选型:SpringBoot + Mybatis Plus(Mybatis) + Dynamic
1. 用MyBatis Plus 生成mapper、xml、service,生成方法。
2. 引用核心jar包
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.4.2</version> </dependency>
3. yml文件配置(有需要连接池配置的可以自己加)
spring: datasource: #配置hikari连接池 hikari: minimum-idle: 4 maximum-pool-size: 16 connection-timeout: 10000 idle-timeout: 30000 connection-init-sql: set names utf8mb4 #动态数据源配置 dynamic: #主数据源 primary: business datasource: #数据源1 business: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db_business?useUnicode=true&characterEncoding=utf-8 username: **** password: **** #数据源2 user: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db_user?useUnicode=true&characterEncoding=utf-8 username: **** password: **** #数据源3 order: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db_order?useUnicode=true&characterEncoding=utf-8 username: **** password: ****
4. 在Service层加DS注解(注意:这个注解要加到mapper.xml文件对应的dao接口层,会报加载失败异常)
@Service @DS(value = "user") public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements UserService { }
bussines, order...库配置是一样的
5. 启动类注解
@MapperScan("com.**.dao") @ComponentScan(value = "com.**") @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
6. 启动项目,看日志输出了如下信息,表示配置成功:
2019-12-16 20:50:52.565 INFO 12896 --- [ main] com.zaxxer.hikari.HikariDataSource : business - Starting... 2019-12-16 20:50:53.611 INFO 12896 --- [ main] com.zaxxer.hikari.HikariDataSource : business - Start completed. 2019-12-16 20:50:53.611 INFO 12896 --- [ main] com.zaxxer.hikari.HikariDataSource : user - Starting... 2019-12-16 20:50:54.100 INFO 12896 --- [ main] com.zaxxer.hikari.HikariDataSource : user - Start completed. 2019-12-16 20:50:54.100 INFO 12896 --- [ main] com.zaxxer.hikari.HikariDataSource : order - Starting... 2019-12-16 20:50:54.607 INFO 12896 --- [ main] com.zaxxer.hikari.HikariDataSource : order - Start completed. 2019-12-16 20:50:54.608 INFO 12896 --- [ main] c.b.d.d.DynamicRoutingDataSource : 初始共加载 3 个数据源 2019-12-16 20:50:54.608 INFO 12896 --- [ main] c.b.d.d.DynamicRoutingDataSource : 动态数据源-加载 business 成功 2019-12-16 20:50:54.608 INFO 12896 --- [ main] c.b.d.d.DynamicRoutingDataSource : 动态数据源-加载 user 成功 2019-12-16 20:50:54.608 INFO 12896 --- [ main] c.b.d.d.DynamicRoutingDataSource : 动态数据源-加载 order 成功 2019-12-16 20:50:54.609 INFO 12896 --- [ main] c.b.d.d.DynamicRoutingDataSource : 当前的默认数据源是单数据源,数据源名为 business