sprinboot 之 mybatis plus + druid多数据源

2022-02-10 10:20:42 浏览数 (1)

0x01:引入 pom 依赖

代码语言:javascript复制
 <!-- 动态数据源 -->
<dependency>
       <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>2.5.4</version>
</dependency>

0x02:yml配置文件

代码语言:javascript复制
spring:
  autoconfigure:
    #自动化配置 例外处理
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    #多数据源配置
    dynamic:
      primary: db1
      datasource:
        # 数据库1
        db1:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
          username: root
          password: root
        # 数据库2
        db2:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/db2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
          username: root
          password: root
      #dynamic - 公共配置
      druid:
        initialSize: 5
        minIdle: 5
        maxActive: 30
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,slf4j,config
        useGlobalDataSourceStat: true
        stat:
          log-slow-sql: true
          merge-sql: true
          slow-sql-millis: 10000

0x03:编写 service 类

在相应service类或方法上添加DS注解

代码语言:javascript复制
package com.olive.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.olive.mapper.UserMapper;
import com.olive.model.mysql.UserEntity;
import com.olive.service.UserService;
import org.springframework.stereotype.Service;

@Service
@DS("db2")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
        //TODO
}
代码语言:javascript复制
参考:https://github.com/baomidou/dynamic-datasource-spring-boot-starter

0 人点赞