赞
踩
在工作中,可能会有些项目会需要两个数据库,一部分操作是对于A数据库,一部分操作对于B数据库,于是在网上寻找方法,最后使用了这个mybatis-plus实现了动态数据源。
搭建一个springboot+mybatis-plus 的项目,然后引入mybatis-plus多数据源配置的依赖
<!-- mybatis plus多数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
这里是配置了两个不同数据类型的数据库,使用了Druid连接池。 端口和用户名密码需要换成自己的
没有使用Druid连接池的把Druid配置删掉就好了,第三步也可以跳过
spring: datasource: dynamic: primary: master # 配置默认数据库 datasource: master: # 数据源1配置 url: jdbc:postgresql://localhost:5432/postgres?currentSchema=zhly username: postgres password: ****** driver-class-name: org.postgresql.Driver slave: # 数据源2配置 url: jdbc:mysql://localhost:3306/zhly?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8 username: root password: ****** driver-class-name: com.mysql.cj.jdbc.Driver durid: initial-size: 5 max-active: 20 min-idle: 10 max-wait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 # 配置一个连接在池中最大生存的时间,单位是毫秒 maxEvictableIdleTimeMillis: 900000 # 配置检测连接是否有效 validationQuery: SELECT 1 testWhileIdle: true testOnBorrow: false testOnReturn: false webStatFilter: enabled: true statViewServlet: enabled: true # 设置白名单,不填则允许所有访问 allow: url-pattern: /druid/* # 控制台管理用户名和密码 login-username: admin login-password: ****** filter: stat: enabled: true # 慢SQL记录 log-slow-sql: true slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: true autoconfigure: # 去除druid配置。是否需要,根据druid连接池的类型。如果druid连接池为starter类型,则需要排除。否则,不需要。 exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
启动类上加上 exclude = {DruidDataSourceAutoConfigure.class
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
如果不使用@DS注解切换数据源,默认使用的就是master 数据源
注意:@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解。
@Service
@DS("slave")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
}
注意:加在类上表示该类中的所有的方法都使用该数据源,也可以加在方法上,方法上注解 优先于 类上注解,括号中的名称是数据源名称,本案例的数据库名称分别为yml文件里面配置的 master 和 slave
具体的演示就不展示出来了,需要的同学可以自行跟着博客去配置,希望能够帮到大家!
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。