读取Nacos配置中心配置信息并修改、上传或删除
如何通过接口获取Nacos配置中心的配置信息?如何通过接口对Nacos配置中心的配置信息进行修改呢?如何通过接口上传到Nacos配置中心新的配置文件呢?如何通过接口对Nacos配置中心的一些配置文件进行删除呢?下面我就把这几个需求的解决方案与大家一起分享一下(如果有不足的地方请大家指教)。
如何操作Nacos配置中心配置信息
想要完成上述操作,第一步就是读取,如何读取,我们要用到一个一个对象,当然 其他的操作也都是通过它来完成的。
ConfigService对象 ,用它进行一系列操作,能满足我们的所有需求,下面我们看一下 ConfigService为我们提供好了什么方法。
我们明显的看到我们想要用的东西:
1. getConfig(String var1, String var2, long var3);获取配置信息。这三个参数的意思为:参数1:dataId 参数2:Group 参数3:请求超时时间
2. publishConfig(String var1, String var2, String var3, String var4);上传修改配置信息。参数1:dataId 参数2:Group 参数3:配置信息。 参数4:你要上传的文件的格式。
3. removeConfig(String var1, String var2);删除配置信息。参数1:dataId 参数2:Group
下面我会说一下这三个方法的使用。
读取Nacos配置信息
//第一步 获取 ConfigService 对象
Properties properties = new Properties();
properties.setProperty("serverAddr", address);
properties.setProperty("namespace", np);
properties.setProperty("username", username);
properties.setProperty("password", password);
ConfigService configService = NacosFactory.createConfigService(properties);
//第二步 获取配置信息 调用API getConfig(String var1, String var2, long var3);
String confStr = configService.getConfig(dataId,groupId,3000);
//判断配置文件是什么格式 根据 dataId 然后解析成JSON格式
if(dataId.endsWith(".yaml")&&StringUtils.isNotEmpty(confStr)){
Yaml yaml = new Yaml();
Map<String,Object> map= yaml.load(confStr);
JSONObject jsonObject=new JSONObject(map);
str=jsonObject.toString();
}else if(dataId.endsWith(".json")&&StringUtils.isNotEmpty(confStr)){
str = confStr;
}
上传Nacos信息
修改也是一样的,只要保证dataId 与group 相同配置文件就会覆盖了。
Properties properties = new Properties();
properties.setProperty("serverAddr", address);
properties.setProperty("namespace", np);
properties.setProperty("username", username);
properties.setProperty("password", password);
//获取Configsetvice
ConfigService configService = NacosFactory.createConfigService(properties);
//这里的dataId 和confMap都是前端传给我的。
if(dataId.endsWith(".yaml")&&confMap!=null&&confMap.size()>0){
Yaml yaml = new Yaml();
confStr = yaml.dumpAsMap(confMap);
if(StringUtils.isNotEmpty(confStr)){
isSuccess = configService.publishConfig(dataId,groupId,confStr,"yaml");
}
}else if(dataId.endsWith(".json")&&confMap!=null&&confMap.size()>0){
JSONObject jsonObject=new JSONObject(confMap);
confStr = jsonObject.toString();
if(StringUtils.isNotEmpty(confStr)) {
isSuccess = configService.publishConfig(dataId, groupId, confStr, "json");
}
}
删除配置信息
删除配置信息 也很简单 只需要两个参数。
Properties properties = new Properties();
properties.setProperty("serverAddr", address);
properties.setProperty("namespace", np);
properties.setProperty("username", username);
properties.setProperty("password", password);
ConfigService configService = NacosFactory.createConfigService(properties);
boolean isSuccess = configService.removeConfig(dataId, groupId);
删除完成功了 会返回一个true。
总结一下 说白了 就是获取到 ConfigService 这个对象就行了,通过它提供的方法去操作。自己对于nacos知识也不是很了解,如果有不对的地方希望指出来~qvq。