写nacos配置

    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<>();

        //找到键,设置新的键值,并将所有键值对放入stringList,用于后面合并为一个字符串
        boolean createKey = true;   //默认增加key-value,key存在时更新key-value
        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);

        //go
        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";
}

你可能感兴趣的:(写nacos配置)