1. 程式人生 > >Spring boot mybatis 配置動態多資料庫

Spring boot mybatis 配置動態多資料庫

新專案用到spring boot框架,在連結多資料來源時,如何配置動態資料庫?看了一圈,網上有很多種方式,如xml配置sqlSessionFactory。或者通過AOP切面的方式,後來想想,總感覺這種方式比較繁瑣,後臺看到一個想法,通過檔案所屬目錄來區分資料庫,我覺得挺好的。

一、SpringBootApplication配置

首先要將spring boot自帶的DataSourceAutoConfiguration禁掉,因為它會讀取application.properties檔案的spring.datasource.*屬性並自動配置單資料來源。在@SpringBootApplication註解中新增

exclude屬性即可:

@EnableFeignClients
@Import(BecloudAutoConfigServiceWrapper.class)
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class})

public class BecloudServicePaymentApplication {

	public static void main(String[] args) {
		SpringApplication.run(BecloudServicePaymentApplication.class, args);
	}
}


二、首先是application.properties配置(路徑:resources/application.properties

# MysqlSQL database -- auth
spring.datasource.auth.url=jdbc:mysql://ip:3306/auth?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true
spring.datasource.auth.username=username
spring.datasource.auth.password=password
spring.datasource.auth.driver-class-name=com.mysql.jdbc.Driver

# PostgreSQL database -- mbox
spring.datasource.mbox.url=jdbc:postgresql://ip:port/mbox?charSet=utf-8
spring.datasource.mbox.username=username
spring.datasource.mbox.password=password
spring.datasource.mbox.driver-class-name=org.postgresql.Driver

# PostgreSQL database -- risk
spring.datasource.risk.url=jdbc:postgresql://ip:port/risk?charSet=utf-8
spring.datasource.risk.username=username
spring.datasource.risk.password=password
spring.datasource.mbox.driver-class-name=org.postgresql.Driver
三、專案目錄結構


四、設定DataSourceConfig.java

import javax.sql.DataSource;

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;

@Configuration
public class DataSourceConfig {
	@Bean(name = "authMasterDS")
	@Primary //主資料庫
    @ConfigurationProperties(prefix = "spring.datasource.auth") // application.properteis中對應屬性的字首
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }
	
	@Bean(name = "mboxMasterDS")
    @ConfigurationProperties(prefix = "spring.datasource.mbox") // application.properteis中對應屬性的字首
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }
	
	@Bean(name = "riskMasterDS")
    @ConfigurationProperties(prefix = "spring.datasource.risk") // application.properteis中對應屬性的字首
    public DataSource dataSource3() {
        return DataSourceBuilder.create().build();
    }
	
}
五、配置SqlSessionFactory

    5.1、

MybatisAuthConfig.java
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@MapperScan(basePackages = {"com.becloud.service.payment.mapper.auth","evo.cloud.auths.dao"}, sqlSessionFactoryRef = "sqlSessionFactory1")//根據basePackages目錄來區分資料庫,訪問該目錄下的mapper檔案,則連結該資料庫
public class MybatisAuthConfig {
	@Autowired
	@Qualifier("authMasterDS")
    private DataSource auth;
	
	@Bean
    public SqlSessionFactory sqlSessionFactory1() throws Exception {
		System.out.println("=====================================================================");
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(auth); // 使用auth資料來源, 連線auth庫
        //掃描對應的mapper檔案
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
           factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/auth/*Mapper.xml"));//resources/mapper目錄最好和src/main/java下面的mapper目錄保持一致,用來注入xml檔案
        return factoryBean.getObject();
    }
	
	@Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory
        return template;
    }
}
 5.2、MybatisMboxConfig
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@MapperScan(basePackages = {"com.becloud.service.payment.mapper.mbox"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisMboxConfig {
	@Autowired
    @Qualifier("mboxMasterDS")
    private DataSource mbox;
	
	@Bean
    public SqlSessionFactory sqlSessionFactory2() throws Exception {
		System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(mbox); // 使用mbox資料來源, 連線mbox庫

        //掃描對應的mapper檔案
      //  factoryBean.setMapperLocations(new Resource[]{new ClassPathResource("mapper/mbox/PayProdMapper.xml")});
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/mbox/*Mapper.xml"));
        return factoryBean.getObject();
    }
	
	@Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2()); // 使用上面配置的Factory
        return template;
    }
}
 5.3、配置MybatisRiskConfig.java
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@MapperScan(basePackages = {"com.becloud.service.payment.mapper.risk"}, sqlSessionFactoryRef = "sqlSessionFactory3")
public class MybatisRiskConfig {
	@Autowired
	@Qualifier("riskMasterDS")
    private DataSource risk;
	
	@Bean
    public SqlSessionFactory sqlSessionFactory3() throws Exception {
		System.out.println("=====================================================================");
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(risk); // 使用risk資料來源, 連線risk庫
        //掃描對應的mapper檔案
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/risk/*Mapper.xml"));
        return factoryBean.getObject();
    }
	
	@Bean
    public SqlSessionTemplate sqlSessionTemplate3() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory3()); // 使用上面配置的Factory
        return template;
    }
}
然後啟動專案:
如果訪問“com.becloud.service.payment.mapper.auth”或者“evo.cloud.auths.dao”路徑下j的mapper類則表示訪問的是auth資料庫。

若訪問的是“com.becloud.service.payment.mapper.mbox”路徑下j的mapper類則表示訪問的是mbox資料庫。