写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";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值