public static String update(RestTemplate restTemplate, NacosConfiguration conf, String key, String value) throws Exception {
String url = String.format("http://%s/nacos/v1/cs/configs?dataId=%s.%s&group=%s&tenant=%s",
conf.getServerAddr(),
conf.getDataId(),
conf.getFileExtension(),
conf.getGroup(),
conf.getNamespace()) ;
String content = restTemplate.getForObject(url,String.class);
log.info("原始内容:{}\n", content);
String[] lines = content.split("\n");
List<String> stringList = new ArrayList<>();
boolean createKey = true;
for(int i=0,len=lines.length; i<len; i++){
String lineString = lines[i];
String[] keyValue = lineString.split("=");
if(keyValue.length>0){
if(keyValue[0].equalsIgnoreCase(key)){
lineString = String.join("=", key, value);
createKey = false;
}
}
stringList.add(lineString);
}
if(createKey){
stringList.add(String.join("=", key, value));
}
content = String.join("\n",stringList);
log.info("变更为:{}\n", content);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("dataId",String.join(".",conf.getDataId(),conf.getFileExtension()));
map.add("group",conf.getGroup());
map.add("content",content);
map.add("type",conf.getFileExtension());
map.add("tenant",conf.getNamespace());
String postUrl = String.format("http://%s/nacos/v1/cs/configs",conf.getServerAddr()) ;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> result = restTemplate.postForEntity(postUrl, request, String.class);
log.info("配置更新结果:{}",result);
return result.getBody();
}
@ConfigurationProperties(prefix = "spring.cloud.nacos.config")
@RefreshScope
@Component
@Data
public class NacosConfiguration {
private String serverAddr;
private String namespace;
@Value("${spring.application.name}")
private String dataId;
private String group = "DEFAULT_GROUP";
private String prefix;
private String fileExtension = "properties";
}