公司现项目是使用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官方文档