springboot 配置多数据源

本文介绍了如何在SpringBoot中配置多数据源,包括通过aop切面和代码方式实现数据源切换。同时,针对使用多数据源时可能出现的问题,如事务中数据源切换无效,文中提供了解决方案,即重写TransactionFactory来确保数据源的正确切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先建一个需要配置的数据源的枚举类 用来切换时候用

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);
        build.setMinimumIdle(20);
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值