若依添加新数据源步骤

本文介绍了如何在SpringBoot项目中通过枚举类定义数据源类型,如MASTERReadOnly,并在DruidConfig中新增配置项以启用Master只读模式,以及如何动态切换数据源。
摘要由CSDN通过智能技术生成

1、数据源枚举类添加MASTERReadOnly数据源
在这里插入图片描述
完整代码

package com.ruoyi.common.enums;

/**
 * 数据源
 * 
 * @author ruoyi
 */
public enum DataSourceType
{
    /**
     * 主库,只写
     */
    MASTER,
    /**
    主库,只读
     */
    MASTERReadOnly,

    /**
     * 中冠数据库
     */
    SLAVE,

    /**
     * 执行数据库
     */
    SLAVE2,

    /**
     * 中交token视图
     */
    SLAVE3,

    /**
     * 用户系统
     */
    DUUS,

    DPMS,

    WALLET
}

2、修改数据源配置类DruidConfig增加masterreadonly bean

    @Bean
    @ConfigurationProperties("spring.datasource.druid.masterreadonly")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.masterreadonly", name = "enabled", havingValue = "true")
    public DataSource masterReadOnlyDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

3、修改DruidConfig类中的DynamicDataSource方法增加MASTERReadOnly

@Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource, DataSource masterReadOnlyDataSource, DataSource slaveDataSource,DataSource slave2DataSource,
                                        DataSource slave3DataSource, DataSource duusDataSource, DataSource dpmsDataSource)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        targetDataSources.put(DataSourceType.MASTERReadOnly.name(), masterReadOnlyDataSource);
        targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
        targetDataSources.put(DataSourceType.SLAVE2.name(), slave2DataSource);
        targetDataSources.put(DataSourceType.SLAVE3.name(), slave3DataSource);
        targetDataSources.put(DataSourceType.DUUS.name(), duusDataSource);
        targetDataSources.put(DataSourceType.DPMS.name(), dpmsDataSource);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}

4、在yml中配置数据源
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值