springboot+mybatis-plus实现多数据源配置并使用

所用pom配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--版本控制中心-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.guozi</groupId>
    <artifactId>mybatis-plus-mutiple-datasource</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--Spring Boot的核心启动器,包含了自动配置、日志和YAML-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--springboot程序测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--springboot web模块支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--MySQL 连接驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- MyBatis-Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.7.1</version>
        </dependency>

        <!--mybatis plus 多数据源-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>2.5.6</version>
        </dependency>

        <!--实体类映射工具-->
        <dependency>
            <groupId>ma.glasnost.orika</groupId>
            <artifactId>orika-core</artifactId>
            <version>1.5.2</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

        <!--阿里巴巴json库-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

        <!--阿里巴巴druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!--google.guava工具类-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>25.1-jre</version>
        </dependency>
    </dependencies>

    <!--maven构建-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

所用yml配置文件

spring:
  aop:
    proxy-target-class: true
    auto: true
  datasource:
    dynamic:
      primary: db1
      datasource:
        db1:
          url: jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=true
          username: root
          password: root
          # 使用druid数据源
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
        db2:
          url: jdbc:mysql://localhost:3306/db2?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=true
          username: root
          password: root
          # 使用druid数据源
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
    # 下面为连接池的补充设置,应用到上面所有数据源中
    druid:
      # 初始化大小,最小,最大
      initialSize: 5
      minIdle: 5
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: true
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
  autoconfigure:
    #DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等。动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错
    exclude:  com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置
mybatis-plus:
  mapper-locations: mapper/**.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.plus.entity.**
  global-config:
    db-config:
      # 自动生成id规则
      id-type: ID_WORKER_STR
  configuration:
    map-underscore-to-camel-case: true
    # sql日志打印
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

测试使用

// 默认数据源db1的dao类
package com.plus.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.plus.entity.TableInfo;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TableInfoDao1 extends BaseMapper<TableInfo> {
     
	
}

// 数据源db2的dao类
package com.plus.dao;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.plus.entity.TableInfo;
import org.apache.ibatis.annotations.Mapper;

@Mapper
@DS("db2")
public interface TableInfoDao2 extends BaseMapper<TableInfo> {
     
	
}

// service类
@Service
public class TableInfoServiceImpl extends ServiceImpl<TableInfoDao1, TableInfo> implements TableInfoService {
     

    @Autowired
    private TableInfoDao1 tableInfoDao1;
    @Autowired
    private TableInfoDao2 tableInfoDao2;

    @Override
    public TableInfoVo queryTableInfo1(String id) {
     
        QueryWrapper<TableInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id", "1");
        TableInfo tableInfo = tableInfoDao1.selectOne(wrapper);
        TableInfoVo vo = new TableInfoVo();
        BeanCopyUtils.copyPart(tableInfo, vo);
        return vo;
    }

    @Override
    public TableInfoVo queryTableInfo2(String id) {
     
        QueryWrapper<TableInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id", "1");
        TableInfo tableInfo = tableInfoDao2.selectOne(wrapper);
        TableInfoVo vo = new TableInfoVo();
        BeanCopyUtils.copyPart(tableInfo, vo);
        return vo;
    }
}

数据库

springboot+mybatis-plus实现多数据源配置并使用_第1张图片

测试结果

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
     PlusApplication.class})
public class TestApplication {
     

    @Autowired
    private TableInfoService tableInfoService;

    @Test
    public void test1(){
     
        System.out.println(tableInfoService.queryTableInfo1("1").getTableName());
        System.out.println(tableInfoService.queryTableInfo2("1").getTableName());
    }
}
// 输出结构
db1
db2

学习感悟:java工具齐全,只要会百度,就有一堆解决方法

你可能感兴趣的:(JAVA)