1:引入nacos背景
推荐系统灰度,需要动态调整灰度的百分比。服务降级兜底,组件升级不让核心服务不可用。保障核心服务百分百高可用。
2:springboot如何配置
1:引入springboot 对应的nacos 配置maven包。
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.7</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.7</version>
</dependency>
2:springboot application 启动引入相关配置如下:
##springboot application 相关配置
@SpringBootApplication
@NacosPropertySources({
@NacosPropertySource(dataId = "com.nacos.recommend.json", autoRefreshed = true),
@NacosPropertySource(dataId = "com.nacos.es.recommend.json", autoRefreshed = true)
})
public class DataApplication {
}
##spring yml 相关配置
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
refresh-enabled: true
enabled: true
namespace: f53d1d2d-79ac-4de3-9c1d-cd50b8350774
group: DEFAULT_GROUP
3:nacos对应的dataId如何动态更新
1:服务器启动的时候主动拉取dataId对应的配置信息,需要在程序中初始化加载。
@NacosInjected
private ConfigService configService;
private Map<String, Object> recommendLocalMap ;
@PostConstruct
public void init() {
try {
String config = configService.getConfig("dataId","dataGroup",3000);
receiveHandleInfo(config);
onReceiveNacosMessage();
} catch (NacosException e) {
logger.error("ERROR IN xxx init failed ");
}
}
public void receiveHandleInfo(String configInfo) {
if (StringUtils.isBlank(configInfo)) {
return;
}
try {
if (StringUtils.isNotBlank(configInfo)) {
recommendLocalMap = JSONObject.parseObject(configInfo, Map.class);
} else {
recommendLocalMap = Maps.newHashMap();
}
} catch (Exception e) {
logger.error("ERROR in receiving nacos config, dataId: " + xxx + ", configInfo: " + configInfo, e);
}
}
2:服务注册listener,配置发生变化以后。由nacos推送给客户端,客户端更新相关配置。
public void onReceiveNacosMessage() throws NacosException {
configService.addListener("dataId", "dataGroup", new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
receiveHandleInfo(configInfo);
}
});
}
4:nacos 配置注意点
1: Context initialization failed java.lang.UnsupportedOperationException: Parsing is not yet supported for this type profile : config 原因:nacos默认是从dataid去获取配置的类型,之前dataId的值为xxx.config ,所以报了上面的的错误。
2: nacos 配置的配置如下:
5:nacos使用总结
nacos 相关的配置可查阅官方文档 :nacos.io/zh-cn/docs/… nacos既可以做为注册中心,也可以做为配置中心。实用性比较强,但是一定要做相关的约定,配置过多会给后人留下坑。在做配置中心之前一定梳理好相关文档说明,方便相关的同学查阅配置说明。