springboot实战代码系列之【集成mybatis-plus和druid实现多数据源切换】

springboot实战代码系列之【集成mybatis-plus和druid实现多数据源切换】

为什么要写本文?

  1. 官方文档给的不够详细,下面是一个能即读即用的版本
  2. 主要也方便自己以后参考代码,不再重复查找

本文使用的springboot版本:2.2.6.RELEASE

添加依赖

查看一下最新版本的插件:https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter

druid插件的最新版也要看看:https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter
不过这里,还是建议看mybatis plus所支持的druid版本。

	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<optional>true</optional>
	</dependency>

	<!--@DS注解需要的依赖-->
	<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
		<version>3.0.0</version>
	</dependency>
	<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>mybatis-plus-boot-starter</artifactId>
		<version>3.3.1</version>
	</dependency>
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid-spring-boot-starter</artifactId>
		<version>1.1.21</version>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>

配置文件

首先要移除Druid自动配置类:

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

某些springBoot的版本上面可能无法排除可用以下方式排除。

spring:
  autoconfigure:
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure

原因:DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找url,username,password等。而我们动态数据源的配置路径是变化的。

然后下面是非常简单的一个druid配置(附录有完整配置):

spring:
  datasource:
    dynamic:
	  # 默认源
      primary: druid-admin
      druid:
        #初始化大小,最小,最大
        initial-size: 5
        min-idle: 5
        max-active: 20
      datasource:
        # 数据源1
        druid-admin:
          url: jdbc:mysql://IP:3306/db_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
          username: xxx
          password: xxx
          driver-class-name: com.mysql.cj.jdbc.Driver
        # 数据源2
        druid-web:
          url: jdbc:mysql://IP:3306/db_web?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
          username: xxx
          password: xxx
          driver-class-name: com.mysql.cj.jdbc.Driver

代码

因为要用分页查询测试,所以加上分页插件

    /**
     * 分页插件,解决分页时total=0问题
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

准备实体类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("t_user")
public class User {
    @TableId(type = IdType.AUTO)
    private Integer id;
    @TableField(value = "user_name")
    private String username;
    private String password;
    private String email;
}

@Data
@TableName("role")
public class Role {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
}

准备mapper

只需要继承BaseMapper得到常用的CRUD接口方法即可,再加上@Mapper注解标识

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jimo.mybatisplusdruiddemo.model.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

@Mapper
public interface RoleMapper extends BaseMapper<Role> {
}

写service层

只需继承ServiceImpl就好。

这里的@DS注解就是选择数据源的,名字与配置里的对应

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jimo.mybatisplusdruiddemo.mapper.UserMapper;
import com.jimo.mybatisplusdruiddemo.model.User;
import org.springframework.stereotype.Service;

@Service
@DS("druid-web")
public class UserService extends ServiceImpl<UserMapper, User> {
}

/**
* 因为默认就是druid-admin库,所以,可以省略,加上也没关系
*/
@Service
//@DS("druid-admin")
public class RoleService extends ServiceImpl<RoleMapper, Role> {
}

测试

测试类非常简单,执行一个分页查询:

@SpringBootTest
class MybatisPlusDruidDemoApplicationTests {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Test
    void testUserService() {
        final int size = 10;
        final Page<User> page = userService.page(new Page<>(1, size));
        assertEquals(size, page.getRecords().size());
        assertTrue(page.getTotal() >= size);
    }

    @Test
    void testRoleService() {
        final int size = 1;
        final Page<Role> page = roleService.page(new Page<>(1, size));
        assertEquals(size, page.getRecords().size());
        assertTrue(page.getTotal() >= size);
    }
}	

可以看到日志里数据库的初始化和销毁:

2020-04-01 10:34:20.661  INFO 15600 --- [           main] j.m.MybatisPlusDruidDemoApplicationTests : No active profile set, falling back to default profiles: default
2020-04-01 10:34:22.805  INFO 15600 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1,druid-admin} inited
2020-04-01 10:34:23.118  INFO 15600 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2,druid-web} inited
2020-04-01 10:34:23.118  INFO 15600 --- [           main] c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource - load a datasource named [druid-admin] success
2020-04-01 10:34:23.119  INFO 15600 --- [           main] c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource - load a datasource named [druid-web] success
2020-04-01 10:34:23.119  INFO 15600 --- [           main] c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource initial loaded [2] datasource,primary datasource named [druid-admin]
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.3.1 
2020-04-01 10:34:24.379  INFO 15600 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-01 10:34:24.888  INFO 15600 --- [           main] j.m.MybatisPlusDruidDemoApplicationTests : Started MybatisPlusDruidDemoApplicationTests in 4.695 seconds (JVM running for 6.375)

...

2020-04-01 10:34:56.112  INFO 15600 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-01 10:34:56.113  INFO 15600 --- [extShutdownHook] c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource start closing ....
2020-04-01 10:34:56.116  INFO 15600 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
2020-04-01 10:34:56.126  INFO 15600 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed
2020-04-01 10:34:56.126  INFO 15600 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} closing ...
2020-04-01 10:34:56.130  INFO 15600 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} closed
2020-04-01 10:34:56.130  INFO 15600 --- [extShutdownHook] c.b.d.d.DynamicRoutingDataSource         : dynamic-datasource all closed success,bye

总结

重点强调

@DS("druid-web")注解用来选择数据源,是可以用在mapper层的

@Mapper
@DS("druid-web")
public interface UserMapper extends BaseMapper<User> {
}

就像有时候偷懒,不想写service层,也可以在mapper就实现多数据源切换:

    @Autowired
    private UserMapper userMapper;

    @Test
    void testUserMapper() {
        final int size = 10;
        final Page<User> page = userMapper.selectPage(new Page<>(1, size), null);
        assertEquals(size, page.getRecords().size());
        assertTrue(page.getTotal() >= size);
    }

附录

druid的完整配置:

spring:
  datasource:
    dynamic:
      primary: druid-admin
      druid:
        #初始化大小,最小,最大
        initial-size: 5
        min-idle: 5
        max-active: 20
        #配置获取连接等待超时的时间
        max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        time-between-eviction-runs-millis: 60000
        #配置一个连接在池中最小生存的时间,单位是毫秒
        min-evictable-idle-time-millis: 300000
        validation-query: SELECT 1 FROM DUAL
        test-while-idle: true
        test-on-borrow: false
        test-on-return: false
        #打开PSCache,并且指定每个连接上PSCache的大小
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
        #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat,wall # 注意这个值和druid原生不一致,默认启动了stat,wall
        filter:
          log4j:
            enabled: true
          wall:
            config:
              # 允许多个语句一起执行
              multi-statement-allow: true
            enabled: true
            db-type: mysql
          stat:
            enabled: true
            db-type: mysql
      datasource:
        # 数据源1
        druid-admin:
          url: jdbc:mysql://IP:3306/db_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
          username: xxx
          password: xxx
          driver-class-name: com.mysql.cj.jdbc.Driver
        # 数据源2
        druid-web:
          url: jdbc:mysql://IP:3306/db_web?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
          username: xxx
          password: xxx
          driver-class-name: com.mysql.cj.jdbc.Driver

参考

  1. https://mybatis.plus/guide/dynamic-datasource.html
  2. https://github.com/baomidou/dynamic-datasource-spring-boot-starter/wiki/Integration-With-Druid
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要在pom.xml中添加依赖,如下: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 然后,需要在application.yml中配置Druid数据源和Mybatis-plus的配置,如下: ```yaml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: root password: root druid: max-active: 20 initial-size: 1 max-wait: 60000 min-idle: 1 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false mybatis-plus: mapper-locations: classpath:/mapper/*.xml global-config: db-config: id-type: auto field-strategy: not_empty table-prefix: t_ logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true ``` 接着,我们需要创建一个数据源切换的工具类,如下: ```java public class DynamicDataSourceContextHolder { private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); public static void setDataSourceType(String dataSourceType) { CONTEXT_HOLDER.set(dataSourceType); } public static String getDataSourceType() { return CONTEXT_HOLDER.get(); } public static void clearDataSourceType() { CONTEXT_HOLDER.remove(); } } ``` 然后,我们需要创建一个切面,用来在方法执行前切换数据源,如下: ```java @Component @Aspect public class DynamicDataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.DataSource)") public void dataSourcePointCut() {} @Around("dataSourcePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); DataSource dataSource = signature.getMethod().getAnnotation(DataSource.class); if (dataSource == null) { DynamicDataSourceContextHolder.setDataSourceType("db1"); } else { DynamicDataSourceContextHolder.setDataSourceType(dataSource.value()); } try { return point.proceed(); } finally { DynamicDataSourceContextHolder.clearDataSourceType(); } } } ``` 在需要使用不同数据源的方法上,我们可以使用@DataSource注解来指定数据源,如下: ```java @DataSource("db2") public List<User> selectUserList() { return userMapper.selectList(null); } ``` 最后,我们需要在配置类中配置多个数据源,如下: ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.druid.db1") public DataSource db1() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid.db2") public DataSource db2() { return DruidDataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource(DataSource db1, DataSource db2) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("db1", db1); targetDataSources.put("db2", db2); DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(); dataSource.setTargetDataSources(targetDataSources); dataSource.setDefaultTargetDataSource(db1); return dataSource; } } ``` 以上就是Mybatis-plus切换Druid数据源的完整代码和配置文件配置。其中,DynamicRoutingDataSource是动态数据源的实现类,需要自行实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值