首先建一个需要配置的数据源的枚举类 用来切换时候用
package com.oncloudsoft.qzhj.common.config;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DataSourceType {
public enum DataBaseType {
QZHJ ,CLOUDODR
}
// 使用ThreadLocal保证线程安全
private static final ThreadLocal<DataBaseType> TYPE = new ThreadLocal<DataBaseType>();
// 往当前线程里设置数据源类型
public static void setDataBaseType(DataBaseType dataBaseType) {
log.info("我来设置数据源了 设置为了{}",dataBaseType);
if (dataBaseType == null) {
throw new NullPointerException();
}
TYPE.remove();
log.info("[将当前数据源改为]:" + dataBaseType);
TYPE.set(dataBaseType);
}
// 获取数据源类型
public static DataBaseType getDataBaseType() {
DataBaseType dataBaseType = TYPE.get() == null ? DataBaseType.QZHJ : TYPE.get();
log.info("[获取当前数据源的类型为]:" + dataBaseType);
return dataBaseType;
}
// 清空数据类型
public static void clearDataBaseType() {
TYPE.remove();
}
}
然后新建一个多数据源的配置类 用来对数据源做一些自定义操作
package com.oncloudsoft.qzhj.common.config;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName 多数据源配置
* @Author zsy
* @Date 2021/12/2 13:23
* @Version 1.0
**/
@Configuration
@Slf4j
public class DataSourceConfig {
/**
* 读取主数据源database1的连接信息
*
* @return DataSourceProperties
*/
@Primary
@Bean(name = "ds1DataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.qzhj")
public DataSource ds1DataSourceProperties() {
HikariDataSource build = (HikariDataSource) DataSourceBuilder.create().build();
build.setMaximumPoolSize(20);
bui