spring boot +MybatisPlus+MySQL配置多数据源及根据包路径进行数据源切换

开始使用csdn

  • 1、设置配置文件
  • 2、新增动态数据源类
  • 3、数据源枚举类
  • 4、修改MybatisPlus配置类
  • 5、数据源切换类
  • 6、AOP切面根据请求访问包路径切换数据源

记录多数据源的配置及使用,本文从网上收集demo,根据自己需求进行整理。

1、设置配置文件

spring boot 多数据源及线程池配置

	spring:
	 datasource:
	    dynamic:
	      druid: # 全局druid参数,绝大部分值和默认保持一致。(现已支持的参数如下,不清楚含义不要乱设置)
	        # 连接池的配置信息
	        # 初始化大小,最小,最大
	        initial-size: 5
	        min-idle: 5
	        maxActive: 20
	        # 配置获取连接等待超时的时间
	        maxWait: 60000
	        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
	        timeBetweenEvictionRunsMillis: 60000
	        # 配置一个连接在池中最小生存的时间,单位是毫秒
	        minEvictableIdleTimeMillis: 300000
	        validationQuery: SELECT 1 FROM DUAL
	        testWhileIdle: true
	        testOnBorrow: false
	        testOnReturn: false
	        # 打开PSCache,并且指定每个连接上PSCache的大小
	        poolPreparedStatements: true
	        maxPoolPreparedStatementPerConnectionSize: 20
	        # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
	        filters: stat,wall,slf4j
	        # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
	        connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
	      datasource:
	        master:
	          url: jdbc:mysql://ip/db?characterEncoding=UTF-8&useUnicode=true&useSSL=false
	          username: username
	          password: password
	          driver-class-name: com.mysql.jdbc.Driver
	        gateway-datasource:
	          url: jdbc:mysql://ip/db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
	          username: username
	          password: password
	          driver-class-name: com.mysql.jdbc.Driver
	          
	      mybatis-plus:
			  mapper-locations: classpath*:org/*/*/**/xml/*Mapper.xml

2、新增动态数据源类

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        String aa = DataSourceContextHolder.getDbType();
        return DataSourceContextHolder.getDbType();
    }
}

3、数据源枚举类

public enum DBTypeEnum {

    dataSourceCms("dataSourceCms"), dataSourceGateway("dataSourceGateway");
    private String value;

    DBTypeEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

4、修改MybatisPlus配置类

MybatisPlus配置类


@Configuration
@MapperScan(value={"org.*.*.**.mapper*"})//指定对应的mapper路径
public class MybatisPlusConfig {

    /**
         *  分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor().setLimit(-1);
    }

    @Bean(name = "dataSourceCms")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
    public DataSource primaryDataSource(){
        return new DruidDataSource();
    }
    @Bean(name = "dataSourceGateway")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.gateway-datasource")
    public DataSource localDataSource(){
        return new DruidDataSource();
    }

    /**
     * 动态数据源配置
     * @return
     */
    @Bean
    @Primary
    public DataSource multipleDataSource (@Qualifier("dataSourceCms") DataSource dataSourceCms,
                                          @Qualifier("dataSourceGateway") DataSource dataSourceGateway ) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map< Object, Object > targetDataSources = new HashMap<>();
        targetDataSources.put(DBTypeEnum.dataSourceCms.getValue(), dataSourceCms );
        targetDataSources.put(DBTypeEnum.dataSourceGateway.getValue(), dataSourceGateway);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(dataSourceCms);
        return dynamicDataSource;
    }

    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource(primaryDataSource(),localDataSource()));
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:org/jeecg/modules/**/xml/*Mapper.xml"));

        MybatisConfiguration configuration = new MybatisConfiguration();
        //configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
//        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(new Interceptor[]{ //PerformanceInterceptor(),OptimisticLockerInterceptor()
                paginationInterceptor() //添加分页功能
        });

        return sqlSessionFactory.getObject();
    }
}

5、数据源切换类

public class DataSourceContextHolder {
    private static final ThreadLocal contextHolder = new ThreadLocal<>(); //实际上就是开启多个线程,每个线程进行初始化一个数据源
    /**
     * 设置数据源
     * @param dbTypeEnum
     */
    public static void setDbType(DBTypeEnum dbTypeEnum) {
        contextHolder.set(dbTypeEnum.getValue());
    }

    /**
     * 取得当前数据源
     * @return
     */
    public static String getDbType() {
        return (String) contextHolder.get();
    }

    /**
     * 清除上下文数据
     */
    public static void clearDbType() {
        contextHolder.remove();
    }
}

6、AOP切面根据请求访问包路径切换数据源

@Aspect
@Component
public class DataBaseAspect {

//    @Pointcut("@annotation(org.jeecg.config.database.DataBase)")

    /**
     * 使用第一个数据源的路径
     */
    @Pointcut("execution(* org.*.*.system.service.impl..*.*(..))" +
            "||execution(* org.*.*.quartz.service.impl..*.*(..)) "
         )
    public void dbPointCut() {

    }

    /**
     * 使用第二个数据源的路径
     */
    @Pointcut("execution(* org.*.*.gateway..*.*(..))")
    public void dbPointCut2() {

    }

    @Before("dbPointCut()")
    public void beforeSwitchDS(JoinPoint point) {
        DataSourceContextHolder.setDbType(DBTypeEnum.dataSourceCms);
    }

    @Before("dbPointCut2()")
    public void change2(JoinPoint point) {
        DataSourceContextHolder.setDbType(DBTypeEnum.dataSourceGateway);
    }

    @After("dbPointCut()")
    public void afterSwitchDS(JoinPoint point) {
        DataSourceContextHolder.clearDbType();
    }
}

你可能感兴趣的:(spring boot +MybatisPlus+MySQL配置多数据源及根据包路径进行数据源切换)