springboot2 連接多數據源

廢話不多說,直接把相關的配置代碼信息貼出來,都是經過項目驗證的,沒有問題的。

數據庫連接配置:

我使用的yml配置文件

spring:
  datasource:
    # 使用druid數據源
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat
    maxActive: 10
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
    #設置removeAbandoned="true"時,當連接池連接數到達(getNumIdle() < 2) and (getNumActive() > getMaxActive() - 3)  [空閒的連接小於2並且活動的連接大於(最大連接-3)] 時便會啓動連接回收,
    #那種活動時間超過removeAbandonedTimeout="1800"的連接將會被回收,
    #同時如果logAbandoned="true"設置爲true,程序在回收連接的同時會打印日誌。
    #removeAbandoned是連接池的高級功能,理論上這中配置不應該出現在實際的生產環境,因爲有時應用程序執行長事務,可能這種情況下,會被連接池誤回收,該種配置一般在程序測試階段,爲了定位連接泄漏的具體代碼位置,被開啓。
    #生產環境中連接的關閉應該靠程序自己保證。
    #先關着
    druid:
      remove-abandoned: true
      log-abandoned: true
      remove-abandoned-timeout: 1800
      filters: wall,stat
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=10000

    shop:
      jdbc-url: jdbc:mysql://${server.ip}:3306/test1?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

    shopdata:
      jdbc-url: jdbc:mysql://${server.ip}:3306/test2?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

 以上的注意點是:

連接url要寫成:jdbc-url

 

數據庫連接掃描的配置類,一個數據庫連接一個配置類。

config1

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;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.xxx.xxx.shop", sqlSessionFactoryRef = "shopSqlSessionFactory")
public class ShopDBSourceConfig {
    /**
     * //自動裝配時當出現多個Bean候選者時,被註解爲@Primary的Bean將作爲首選者,否則將拋出異常
     * // prefix 指向的是配置文件中的數據庫連接額前綴信息
     */
    @Bean(name = "shopSource")
    @ConfigurationProperties("spring.datasource.shop")
    @Primary
    public DataSource shopDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "shopSqlSessionFactory")
    @Primary//自動裝配時當出現多個Bean候選者時,被註解爲@Primary的Bean將作爲首選者,否則將拋出異常
    public SqlSessionFactory sqlSessionFactory(@Qualifier("shopSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/shop/*.xml"));
        return bean.getObject();
    }

    /**
     * 事物管理
     */
    @Bean(name = "shopTransactionManager")
    @Primary//自動裝配時當出現多個Bean候選者時,被註解爲@Primary的Bean將作爲首選者,否則將拋出異常
    public DataSourceTransactionManager shopTransactionManager(@Qualifier("shopSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "shopSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate shopSqlSessionTemplate(
            @Qualifier("shopSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

basePackages : DAO文件的存放路徑(增刪改查的接口)

config2

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;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.xxx.xxx.shopdata", sqlSessionFactoryRef = "shopdataSqlSessionFactory")
public class ShopDataDBSourceConfig {
    /**
     * //自動裝配時當出現多個Bean候選者時,被註解爲@Primary的Bean將作爲首選者,否則將拋出異常
     * // prefix 指向的是配置文件中的數據庫連接額前綴信息
     */
    @Bean(name = "shopdataSource")
    @ConfigurationProperties(prefix = "spring.datasource.shopdata")
    public DataSource shopdataDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "shopdataSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("shopdataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/shopdata/*.xml"));
        return bean.getObject();
    }

    /**
     * 事物管理
     */
    @Bean(name = "shopdataTransactionManager")
    public DataSourceTransactionManager shopdataTransactionManager(@Qualifier("shopdataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "shopdataSqlSessionTemplate")
    public SqlSessionTemplate shopdataSqlSessionTemplate(
            @Qualifier("shopdataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

 

使用數據庫事務:

@Transactional(transactionManager = "shopTransactionManager", rollbackFor = Exception.class)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章