springboot mysql 多数据源处理(相同+完全独立)

#database1
spring.datasource.wh.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.wh.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.wh.jdbcUrl=jdbc:mysql://192.168.1.130:3306/wh?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.wh.username=root
spring.datasource.wh.password=root
spring.datasource.wh.minimum-idle=1
spring.datasource.wh.maximum-pool-size=15
spring.datasource.wh.auto-commit=true
spring.datasource.wh.idle-timeout=60000
spring.datasource.wh.pool-name=wuhan
spring.datasource.wh.max-lifetime=1800000
spring.datasource.wh.connection-timeout=30000
spring.datasource.wh.connection-test-query=SELECT 1

#database2
spring.datasource.es.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.es.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.es.jdbcUrl=jdbc:mysql://192.168.1.130:3306/es?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.es.username=root
spring.datasource.es.password=root
spring.datasource.es.minimum-idle=1
spring.datasource.es.maximum-pool-size=15
spring.datasource.es.auto-commit=true
spring.datasource.es.idle-timeout=60000
spring.datasource.es.pool-name=enshi
spring.datasource.es.max-lifetime=1800000
spring.datasource.es.connection-timeout=30000
spring.datasource.es.connection-test-query=SELECT 1
 


import com.zaxxer.hikari.HikariDataSource; 
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.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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源ben
 */
@MapperScan(basePackages = "xxx.xx.mapper")
@Configuration
public class DynamicDataSourceConfiguration {

    /**
     * 武汉数据源
     * @return
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.wh")
    public DataSource wuhan(){
        return new HikariDataSource();
    }

    /**
     * 恩施数据源
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.es")
    public DataSource enshi(){
        return new HikariDataSource();
    }

    /**
     * 核心动态数据源配置
     * @return
     */
    @Bean
    public DataSource dynamicDataSource(){
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        Map<Object,Object> dataSourceMap = new HashMap<>(2);
        //设置默认数据源
        dataSource.setDefaultTargetDataSource(wuhan());
        //配置数据源
        dataSourceMap.put(CityEnum.wuhan.getCity(),wuhan());
        dataSourceMap.put(CityEnum.enshi.getCity(),enshi());
        dataSource.setTargetDataSources(dataSourceMap);
        return dataSource;
    }

    /**
     * sql工厂
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        //此处设置为了解决找不到mapper文件的问题
        sqlSessionFactoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapping/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * sql模板
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }

    /**
     * 事务管理
     * @return
     */
    @Bean
    public PlatformTransactionManager platformTransactionManager(){
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}


public class DataSourceHolder {
    //线程本地环境
    private static final ThreadLocal<String> contextHolders = new ThreadLocal<>();

    //设置数据源
    public static void setDataSource(String customerType) {
        contextHolders.set(customerType);
    }

    //获取数据源
    public static String getDataSource() {
        return contextHolders.get();
    }

    //清除数据源
    public static void clearDataSource() {
        contextHolders.remove();
    }

}
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {


    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSource();
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SpringWebConfig implements WebMvcConfigurer {

    @SuppressWarnings("unused")
    @Autowired
    private DynamicDataSourceInterceptor dynamicDataSourceInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(dynamicDataSourceInterceptor);
    }
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author best
 */
@Component
public class DynamicDataSourceInterceptor implements HandlerInterceptor {

    //在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String city = request.getHeader("city");
        if (StringUtils.isBlank(city)) {
            city = CityEnum.wuhan.getCity();
        }
        DataSourceHolder.setDataSource(city);
        //RequestCityHolder.add(city);
        System.err.println(city + "处理开始...");
        return true;
    }

    //请求完成之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String city = request.getHeader("city");
        if (StringUtils.isBlank(city)) {
            city = CityEnum.wuhan.getCity();
        }
        //清除数据源
        DataSourceHolder.clearDataSource();
        //清除ThreadLocal变量
        //RequestCityHolder.remove();
        System.err.println(city + "处理完成...");
    }
}

public enum CityEnum {
    /*武汉*/
    wuhan("wuhan"),
    /*恩施*/
    enshi("enshi");

    private String city;

    CityEnum(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }
}

你可能感兴趣的:(springboot,mysql)