Spring Boot 多数据源项目搭建

一.项目基本结构
common:公用包,包含枚举,错误参数定义,静态变量参数等;config:配置文件包;pojo:对象,实体类包;utils:工具类包

二.详细内容
1.项目配置文件(yml):
此项目配置两个数据源,一个是本机地址,一个是腾讯云搭建的私服
ps:springboot使用的是1.5.9版本,若使用2.x.x版本,项目地址:server:servlet:context-path: /xxxx

2.配置文件包(config)
在这里插入图片描述
2.1 MybatisPlusConfig:配置mybatis相关数据(也可在yml中配置),启动加载多个数据源;

@EnableTransactionManagement
@Configuration
@MapperScan("com.hy.testtwo.**.mapper.db*")
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLocalPage(true);
        return paginationInterceptor;
    }

    /**
     * 路径为配置文件中数据源路径
     * @return
     */
    @Bean(name = "db1")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource db1() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "db2")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db2")
    public DataSource db2() {
        return DruidDataSourceBuilder.create().build();
    }


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

    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource(db1(), db2()));

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

2.2 DymamicDataSource:动态数据源决策

@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        log.info("获取数据源");
        return  DbContextHolder.getDbType();
    }
}

2.3 DataSourceSwitchAspect: Aop实现数据源切换

@Aspect
@Order(value = -100)
@Component
@Slf4j
public class DataSourceSwitchAspect {

    @Pointcut("execution(* com.hy.testtwo.mapper.db1..*.*(..))")
    private void db1Aspect() {
        log.info("db1");
    }

    @Pointcut("execution(* com.hy.testtwo.mapper.db2..*.*(..))")
    private void db2Aspect() {
        log.info("db2");
    }
    
    @Before("db1Aspect()")
    public void db1() {
        log.info("切换到db1 数据源...");
        DbContextHolder.setDbType(DBTypeEnum.db1);
    }

    @Before("db2Aspect()")
    public void db2() {
        log.info("切换到db2 数据源...");
        DbContextHolder.setDbType(DBTypeEnum.db2);
    }

}

2.4 DbContextHolder:设置获取数据源

public class DbContextHolder {

    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();
    }
}

3.逻辑代码
此项目为开发方便,使用jpa,lombok,swagger等工具,dao层,controller层详细代码此处略过;service层仅贴出实现类部分代码:

@Resource
    private TestRecordInfoMapper infoMapper;

    @Resource
    private TestRecordMemoryMapper memoryMapper;

    @Override
    public BaseRespVo<TestRecordInfoEntity> queryById(Integer id) {
//        Optional<TestRecordInfoEntity> entity = infoMapper.findById(id);
//        if (!entity.isPresent()){
//            return BaseRespVo.error(IError.DATA_NOT_EXIST);
//        }
//        return BaseRespVo.success(entity.get());
        TestRecordInfoEntity entity = infoMapper.findOne(id);
        return BaseRespVo.success(entity);
    }

    @Override
    public BaseRespVo<TestRecordMemoryEntity> queryByIdForMeory(Integer id) {
        TestRecordMemoryEntity entity = memoryMapper.findOne(id);
        return BaseRespVo.success(entity);
    }
ps:注解部分为spring2.0以上版本jpa查询相关代码

三 gitee地址:
https://gitee.com/HuangyinGl/hytests.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值