1. 程式人生 > >spring boot 配置多資料來源

spring boot 配置多資料來源

1.application.yml配置

server:
  port: 8088
spring:
    http:
      multipart:
        max-file-size: 50Mb
        max-request-size: 50Mb
        enabled: true
    datasource:
      primary:
        name: test
        url: jdbc:mysql://116.62.23.45:3306/asd2?useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
        #url: jdbc:mysql://118.31.37.175:3306/asd_dev?useUnicode=true&characterEncoding=UTF-8
        #username: root
        #password: zhezhuo408
        # 使用druid資料來源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20


    #資料來源2
      secondary:
        name: test
        url: jdbc:mysql://116.62.23.45:3306/asd_test1?useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
        #url: jdbc:mysql://118.31.37.175:3306/asd_dev?useUnicode=true&characterEncoding=UTF-8
        #username: root
        #password: zhezhuo408
        # 使用druid資料來源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
    redis:
      host: 127.0.0.1
      port: 6379
    application:
      name: webapi
mybatis:
  mapper-locations: classpath:mapping/**/*.xml
  type-aliases-package: com.aishidai.app.model.pojo.*
  check-config-location: true
  config-location: classpath:mybatis-config.xml
logging:
  level:
    org.springframework.web: DEBUG
    com.aishidai.app.dao: DEBUG
alishidai: testHolleWrod
ribbon:
  eager-load:
    enabled: false

2.寫兩個資料來源類

ALLMybatisConfig:

package com.aishidai.app.config;

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.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @MapperScan來掃描註冊mybatis資料庫介面類,其中basePackages屬性表明介面類所在的包,
 * sqlSessionTemplateRef表明介面類使用的SqlSessionTemplate(MyBatis提供的持久層訪問模板化的工具,
 * 執行緒安全,
 * 可通過構造引數或依賴注入SqlSessionFactory例項)。如果專案需要配置兩個資料庫,
 * @MapperScan也需要分別配置。
 */
@Configuration
@MapperScan(basePackages = {"com.aishidai.app.dao"},sqlSessionTemplateRef = "allSqlSessionTemplate")
public class AllMybatisConfig {

    @Bean(name="allDataSource")
    @Primary//必須加此註解,不然報錯,下一個類則不需要新增,@Primary註解的例項優先於其他例項被注入
    //SpringBoot 是通過@ConfigurationProperties來獲取配置資訊,
    // @ConfigurationProperties 使用方式有兩種 1、在類上使用該註解 2、在工廠方法上使用該註解 (@bean)
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource allDataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean//@Qualifier限定描述符除了能根據名字進行注入,更能進行更細粒度的控制如何選擇候選者
    public SqlSessionFactory allSqlSessionFactory(@Qualifier("allDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //新增xml目錄
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
       try {
             bean.setMapperLocations(resolver.getResources("classpath*:mapping/**/*.xml"));
             return bean.getObject();
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException(e);
                }
    }
    @Bean
    public SqlSessionTemplate allSqlSessionTemplate(@Qualifier("allSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        //使用上面配置的Facyory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }

}

OrderMybatisConfig:

package com.aishidai.app.config;

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.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 配置資料來源2
 */
@Configuration
@MapperScan(basePackages = {"com.aishidai.app.dao1"},sqlSessionTemplateRef = "orderSqlSessionTemplate")
public class OrderMybatisConfig {

    @Bean("orderDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource orderDataSource(){
     return DataSourceBuilder.create().build();
}
  @Bean
  public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
  }
  @Bean
  public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception{
      SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
      bean.setDataSource(dataSource);
      //新增xml目錄
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      try {
          bean.setMapperLocations(resolver.getResources("classpath:mapping1/*.xml"));
          return bean.getObject();
      } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException(e);
      }

  }


}

3.啟動類配置

package com.aishidai.app.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
              
/**
 * Springboot 啟動類
 */
@SpringBootApplication
@ServletComponentScan(basePackages = "com.aishidai")
@ComponentScan(basePackages = "com.aishidai")
@EnableCaching //開啟快取
//@MapperScan(basePackages = {"com.aishidai.app.dao"})//掃描 包下相應的class 主要是mybatis 的持久化類
//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class App {

   public static void main(String[] args) {
      System.out.printf("================開始啟動===========");
      SpringApplication.run(App.class, args);
   }
}

4.具體的例子不再書寫