SpringCloud项目中使用Nacos配置中心管理Redisson配置文件

公司现项目是使用redisson作为redis客户端来使用的,虽然公司使用了nacos作为作为配置中心,但是redisson一直是通过各个项目中本地配置文件来使用的,因此有了把配置文件移到nacos中管理的需求。

redisson-spring-boot-starter中对于在将配置文件发布到配置中心中保管的支持似乎不太完善,也可能是我没有找到正确的方式,因此我选择了使用官方文档中自定义RedissonClient的方式来完成从nacos中读取配置文件,并使用nacos提供的javaSDK来完成从配置中心中读取配置文件。

@Configuration
public class RedissonConfiguration {

@Value("${spring.redisson.dataId}")
private String dataId;

@Value("${spring.redisson.group}")
private String group;

    @Autowired
    private NacosConfigManager nacosConfigManager;

    @Bean
    public RedissonClient redisson()throws NacosException, IOException {
        ConfigService configService =nacosConfigManager.getConfigService();
        String config = configService.getConfig(dataId, group, 3000);
        return Redisson.create(Config.fromYAML(config));
    }
}

然后通过在配置文件中,配置dataId和group等参数来定位redisson配置文件,nacos中创建相应的配置文件


spring:

  redisson:

    dataId: single-model-local.yml

    group: my-group

顺便一提,也可以不使用NacosConfigManager ,使用NacosFactory的方式来读取配置文件;NacosFactory的createConfigService方法可以通过传入一个Properties对象的方式来构建ConfigService对象,使用这种方法需要在Properties对象中传入配置文件的地址以及命名空间,并且如果项目中的nacos启用了获取配置时认证权限,还需要在Properties中传入nacos的用户名和密码,否则在读取配置文件的时候会返回 403 unknown user 的错误

com.alibaba.nacos.api.exception.NacosException:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Jul 28 10:58:15 CST 2021

There was an unexpected error (type=Forbidden, status=403).

unknown user!

以下是使用这种方式的代码

@Bean
RedissonClient redisson()throws NacosException, IOException {
Properties properties =new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR,serverAddr);
        properties.put(PropertyKeyConst.NAMESPACE,nameSpace);
        properties.put("username","nacos");
        properties.put("password","nacos");
        ConfigService configService = NacosFactory.createConfigService(properties);
        String config = configService.getConfig(dataId, group, 3000);
        return Redisson.create(Config.fromYAML(config));
    }
}

说的不一定准确,仅作为笔记记录下来,供自己未来不再掉坑里,如果对其他人有帮助,我感到很荣幸。
参考文档:
nacos javaSDK官方文档
redisson官方文档

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容