开发者社区 > 博文 > springboot实战代码系列之【集成mybatis-plus和druid实现多数据源切换】
分享
  • 打开微信扫码分享

  • 点击前往QQ分享

  • 点击前往微博分享

  • 点击复制链接

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

  • 京东城市JUST团队
  • 2021-01-18
  • IP归属:未知
  • 31440浏览

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条评论