springboot+mybatis+Druid配置多数据源(mysql+postgre)

Posted ziyue7575

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot+mybatis+Druid配置多数据源(mysql+postgre)相关的知识,希望对你有一定的参考价值。

springboot+mybatis+Druid配置多数据源(mysql+postgre)

参考资料:

第八章 springboot + mybatis + 多数据源
springboot + mybatis + druid + 多数据源
springBoot 动态数据源以及Mybatis多数据源
springboot - mybatis连接多数据源(动态)

引入pom依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
        <!--阿里druid数据库链接依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--事务管理:原子性,一致性,隔离性,持久性-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
         <!--mysql数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--postgresql数据库-->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

设置application多数据源

只是在原有的数据库配置外层添加了db1,db2,用来区分数据库;

注意:url使用的是jdbc的jdbc-url

durid无需改变

spring:
  datasource:
    db1: #配置数据源1:此处配置的mysql数据库
      driverClassName: com.mysql.jdbc.Driver
      username: root
      password: 123456
      # spring2.0此处为jdbc-url
      jdbc-url: jdbc:mysql://127.0.0.1:3306/aa?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
      type: com.alibaba.druid.pool.DruidDataSource
    db2: #配置数据源2,此处配置的是postgre数据库
      jdbc-url: jdbc:postgresql://127.0.0.1:5432/test1
      username: postgres
      password: 123456
      driverClassName: org.postgresql.Driver
  #    platform: postgres
      type: com.alibaba.druid.pool.DruidDataSource
      initialization-mode: always
    # ============================== druid ============================== #
    druid:
      #最大活跃数
      maxActive: 20
      #初始化数量
      initialSize: 1
      #最大连接等待超时时间
      maxWait: 60000
      #打开PSCache,并且指定每个连接PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      #通过connectionProperties属性来打开mergeSql功能;慢SQL记录
      #connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 1 from dual
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,\'wall\'用于防火墙
      filters: stat, wall, log4j

config配置

注意:两个数据库的xml文件和mapper文件需要分开放置

1551151878188

1551151885859

db1config配置(主数据库配置)

注意:db1设置为了主数据库,则需要配置注解@Primary

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**主数据源mysql配置(需要加@Primary)
* mysql data source config
*
* @author 荆世玉
* @date 2019/2/26 9:07:16
* @description postgresql data source config
*/
@Configuration
//注入mapper
@MapperScan(basePackages = "net.cc.commons.mapper.mysql.**", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DataSource1Config {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.db1")//设置配置
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置对应的xml文件位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/mysql/*.xml"));
        return bean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Primary
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

db2config配置(其他数据库)

注意:

1.虽然数据库不同,但是配置相同,只是其他数据库不需要添加@Primary注解;

2.bean的名字不能重复

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
* postgresql 配置(无需@Primary)
*
* @author 荆世玉
* @date 2019/2/26 9:07:16
* @description postgresql data source config
*/
@Configuration
//注入mapper
@MapperScan(basePackages = "net.cc.commons.mapper.postgre.**", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DataSource2Config {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/postgre/*.xml"));
        return bean.getObject();
    }

    @Bean
    public DataSourceTransactionManager db2TransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

事务处理

注入事务的时候需要标明对应数据库(主数据库可以不用设置)

如:db2的数据库的事务"

@Transactional(value = "db2TransactionManager")

mapper层

不同数据库的mapper文件不能载同一个包中,config在注入时会注入错误;

使用时,与单数据源时一致

    @Select("select * from table_1 ")
    public List<Table1> all();
    public List<Table1> all2();
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.cc.commons.mapper.mysql.MysqlMapper">
    <select id="all2" resultType="net.cc.commons.entity.Table1">
       select * from table_1
    </select>
</mapper>
[{"id1":1,"id2":23,"id3":2222},{"id1":2,"id2":2222,"id3":111}]




以上是关于springboot+mybatis+Druid配置多数据源(mysql+postgre)的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot系列七:SpringBoot 集成 MyBatis事物配置及使用druid 数据源druid 监控使用

SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页

SpringBoot + mybatis + druid 配置两个数据源

SpringBoot--整合Mybatis+druid

springboot + mybatis +druid

SpringBoot MyBatis druid数据库连接池