一、导入依赖
<!--配置多数据源--> <dependency> <groupid>com.baomidou</groupid> <artifactid>dynamic-datasource-spring-boot-starter</artifactid> <version>3.5.0</version> </dependency>
二、配置文件
spring: type: com.alibaba.druid.pool.druiddatasource datasource: dynamic: primary: master #设置默认的数据源或者数据源组,默认值即为master strict: true #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源 datasource: master: username: root password: root123. url: jdbc:mysql://120.27.15.101:3306/policy?useunicode=true&characterencoding=utf8&charactersetresults=utf8 driver-class-name: com.mysql.cj.jdbc.driver slave_1: username: root password: zxc12300824. url: jdbc:mysql://localhost/test?useunicode=true&characterencoding=utf8&charactersetresults=utf8 driver-class-name: com.mysql.cj.jdbc.driver
三、在启动类上配置
@springbootapplication(exclude={datasourceautoconfiguration.class})
四、在需要切换数据源的类上、方法上使用@ds注解
一般是用在mapper、service
结论
本篇文章介绍了在实际开发过程中实现多数据源切换的方式:使用@ds注解,从而实现数据源的切换。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论