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}]





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM