spring boot 之 集成mybatis-plus、druid整合多数据源

spring boot 版本:2.3.12.RELEASE
MySQL 版本:8.0

数据表准备

-- 数据库 test1
CREATE TABLE `t_product` (
  `id` int NOT NULL AUTO_INCREMENT,
  `produce_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `produce_price` int DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;
-- 数据库 test2
CREATE TABLE `student` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

引入pom文件依赖

<!--spring-boot-starter-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!--spring-boot-starter-web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--spring-boot-starter-test-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.26</version>
</dependency>
<!--Mybatis-Plus 注意版本-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
<!--dynamic-datasource-spring-boot-starter-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<!--druid-spring-boot-starter-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.16</version>
</dependency>
<!-- mysql-connector-j -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
</dependency>

application.yml配置文件

spring:
  autoconfigure:
    exclude:  com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    dynamic:
      primary: master
      datasource:
        master:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://1.1.1.1:3306/test1?allowMultiQueries=true&serverTimezone=Asia/Shanghai&useSSL=false
          username: root
          password: 123456
        slave:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://2.2.2.2:3306/test2?allowMultiQueries=true&serverTimezone=Asia/Shanghai&useSSL=false
          username: root
          password: 654321
    druid:
      # 如果initialSize数量较多时,打开会加快应用启动时间
      async-init: true
      # 连接池初始化时创建的连接数
      initial-size: 5
      # 连接池中最大连接数
      max-active: 50
      # 连接池中最小空闲连接数
      min-idle: 5
      # 连接池中最大空闲连接数
      max-idle: 20
      # 配置获取连接等待超时的时间 毫秒
      max-wait: 6000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 增强timeBetweenEvictionRunsMillis的周期性连接检查,minIdle内的空闲连接,每次检查强制验证连接有效性
      keep-alive: true
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      max-evictable-idle-time-millis: 172800000
      # 用于检测连接是否有效的SQL语句
      validation-query: select 1
      validation-query-timeout: 1
      # 是否开启空闲连接的检测
      test-while-idle: true
      # 是否开启连接的检测功能,在获取连接时检测连接是否有效
      test-on-borrow: false
      # 是否开启连接的检测功能,在归还连接时检测连接是否有效
      test-on-return: false
      # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
      pool-prepared-statements: false

      filter:
        stat:
          enabled: true
          db-type: mysql
          log-slow-sql: true
          slow-sql-millis: 3000
          connection-stack-trace-enable: true
        wall:
          enabled: true
          db-type: mysql
          config:
            insert-allow: true
            delete-allow: false
            update-allow: true
            drop-table-allow: false
      stat-view-servlet:
        # http://localhost:8989/mp/druid/index.html
        # 启用StatViewServlet
        enabled: true
        # 访问内置监控页面的路径,内置监控页面的首页是/druid/index.html
        url-pattern: /druid/*
        # 不允许清空统计数据,重新计算
        reset-enable: false
        # 配置监控页面访问密码
        login-username: root
        login-password: 123456
        # 允许访问的地址,如果allow没有配置或者为空,则允许所有访问
        allow: 127.0.0.1
        # 拒绝访问的地址,deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝
        
mybatis-plus:
  # 实体类Mapper.xml文件所在包
  mapper-locations: classpath:mapper/*Mapper.xml
  # 指定 MyBatis 别名包扫描路径,用于给包中的类注册别名。注册后,在 Mapper 对应的 XML 文件中可以直接使用类名,无需使用全限定类名。
  type-aliases-package: com.sun.pojo
  configuration:
    # 开启驼峰映射,A_COLUMN > aColumn
    map-underscore-to-camel-case: true
    # 是否允许单条sql 返回多个数据集
    multiple-result-sets-enabled: true
    # mybatis-plus的日志输出到控制台
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

新建实体类

@Data
@TableName("t_product")
public class Product {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @TableField("produce_name")
    private String produceName;

    @TableField("produce_price")
    private String producePrice;

}
@Data
@TableName("student")
public class Student {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @TableField("remark")
    private String remark;
}

新建mapper

mapper层类上使用@DS()注解区分使用的数据源

@DS("master")
@Mapper
public interface ProductMapper extends BaseMapper<Product> {
}
@DS("slave")
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}

新建测试类

@SpringBootTest
@RunWith(SpringRunner.class)
public class DataTest {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ProductMapper productMapper;

    @Test
    public void dataTest() {
        LambdaQueryWrapper<Student> studentWrapper = new LambdaQueryWrapper<>();
        List<Student> studentList = studentMapper.selectList(studentWrapper);
        studentList.forEach(System.out::println);

        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        List<Product> productList = productMapper.selectList(productWrapper);
        productList.forEach(System.out::println);
    }
    
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值