通過Java修改consul配置(保留註釋、保留縮進)

 

 

 

 

 

  直接上代碼了,找了很久也沒找到保留註釋的三方包,snakeyaml 的縮進一直也有問題,就自己寫了個正則方式的

  consul也沒有相關接口,只接受整個的

  傳key和value,替換相應value值,

  大佬有更好的方法希望能告訴我

<dependency>
    <groupId>com.orbitz.consul</groupId>
    <artifactId>consul-client</artifactId>
    <version>1.5.3</version>
</dependency>

  

 

 

package com.qpaas.migration;

import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main3 {


    public static void main(String[] args) {
        String consulUrl = "xx";
        String consulKey = "xx";
//        String propertyKey = "server.port";
//        String newValue = "8081";
//        String yamlContent = "server:\n  port: 28082 #xxxx\nspring:\n  mail:\n    host: 3333\n    username: 1111\n    password: 222";
        try {
            // 構建Consul客戶端
            Consul consul = Consul.builder().withUrl(consulUrl).build();
            KeyValueClient kvClient = consul.keyValueClient();

            // 讀取當前的YAML值
            String currentYaml = kvClient.getValueAsString(consulKey)
                    .orElseThrow(() -> new RuntimeException("無法找到配置項:" + consulKey));


            // 示例1: 修改server.port的值爲9091
            String keyToFind1 = "server.port";
            String newValue1 = "9091";
            currentYaml = updateYml(keyToFind1, newValue1, currentYaml);


            String keyToFind2 = "spring.mail.host";
            String newValue2 = "xxxxx";
            currentYaml = updateYml(keyToFind2, newValue2, currentYaml);

            // 輸出更新後的YAML內容
            System.out.println(currentYaml);

            // 更新Consul中的值
            kvClient.putValue(consulKey, currentYaml);

            System.out.println("Value updated successfully!");

        } catch (Exception e) {
            System.err.println("An error occurred while updating the value in Consul: " + e.getMessage());
        }
    }



    public static String updateYml(String keyToFind, String newValue, String yamlContent) {
        String pathRegex1 = keyToRegex(keyToFind);

        Pattern pathPattern1 = Pattern.compile(pathRegex1, Pattern.MULTILINE);
        Matcher pathMatcher1 = pathPattern1.matcher(yamlContent);

        String pathRegex2 = buildRegexForKey(keyToFind);
        Pattern pathPattern2 = Pattern.compile(pathRegex2, Pattern.MULTILINE);
        Matcher pathMatcher2 = pathPattern2.matcher(yamlContent);

        if (pathMatcher1.find() && pathMatcher2.find()) {
            String replacement1 = pathMatcher2.group(0);
            String replacement2 = pathMatcher1.group(0) + " " + newValue;

            yamlContent = yamlContent.replaceFirst(replacement1, replacement2);
            System.out.println("The YAML content has been updated. The value of " + keyToFind + " is now: " + newValue);
        } else {
            System.out.println("The key " + keyToFind + " was not found in the YAML content.");
        }
        return yamlContent;
    }

    public static String keyToRegex(String key) {
        String[] parts = key.split("\\.");
        StringBuilder regexBuilder = new StringBuilder();
        for (String part : parts) {
            regexBuilder.append("\\b").append(part).append("\\b\\s*:"); // Match the key and following colon
            if (!part.equals(parts[parts.length - 1])) {
                regexBuilder.append("\\s*\\n\\s*"); // Add newline and indentation for all parts except the last one
            }
        }
        return regexBuilder.toString();
    }
    private static String buildRegexForKey(String key) {
        String[] parts = key.split("\\.");
        StringBuilder regexBuilder = new StringBuilder();

        // 匹配每個部分的鍵和冒號,考慮到YAML的縮進
        for (String part : parts) {
            if (regexBuilder.length() > 0) {
                // 如果不是第一個部分,添加縮進匹配(兩個空格)
                regexBuilder.append("\\n\\s*");
            }
            regexBuilder.append("\\b").append(part).append(":\\s*");
        }
        regexBuilder.append("[^\\s\\n]+"); // 匹配值直到下一個空白字符或換行符

        return regexBuilder.toString();
    }
}


  

 

 

 

 

 


package com.qpaas.migration; import com.orbitz.consul.Consul; import com.orbitz.consul.KeyValueClient; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main3 { public static void main(String[] args) { String consulUrl = "xx"; String consulKey = "xx"; // String propertyKey = "server.port"; // String newValue = "8081"; // String yamlContent = "server:\n port: 28082 #xxxx\nspring:\n mail:\n host: 3333\n username: 1111\n password: 222"; try { // 構建Consul客戶端 Consul consul = Consul.builder().withUrl(consulUrl).build(); KeyValueClient kvClient = consul.keyValueClient(); // 讀取當前的YAML值 String currentYaml = kvClient.getValueAsString(consulKey) .orElseThrow(() -> new RuntimeException("無法找到配置項:" + consulKey)); // 示例1: 修改server.port的值爲9091 String keyToFind1 = "server.port"; String newValue1 = "9091"; currentYaml = updateYml(keyToFind1, newValue1, currentYaml); String keyToFind2 = "spring.mail.host"; String newValue2 = "xxxxx"; currentYaml = updateYml(keyToFind2, newValue2, currentYaml); // 輸出更新後的YAML內容 System.out.println(currentYaml); // 更新Consul中的值 kvClient.putValue(consulKey, currentYaml); System.out.println("Value updated successfully!"); } catch (Exception e) { System.err.println("An error occurred while updating the value in Consul: " + e.getMessage()); } } public static String updateYml(String keyToFind, String newValue, String yamlContent) { String pathRegex1 = keyToRegex(keyToFind); Pattern pathPattern1 = Pattern.compile(pathRegex1, Pattern.MULTILINE); Matcher pathMatcher1 = pathPattern1.matcher(yamlContent); String pathRegex2 = buildRegexForKey(keyToFind); Pattern pathPattern2 = Pattern.compile(pathRegex2, Pattern.MULTILINE); Matcher pathMatcher2 = pathPattern2.matcher(yamlContent); if (pathMatcher1.find() && pathMatcher2.find()) { String replacement1 = pathMatcher2.group(0); String replacement2 = pathMatcher1.group(0) + " " + newValue; yamlContent = yamlContent.replaceFirst(replacement1, replacement2); System.out.println("The YAML content has been updated. The value of " + keyToFind + " is now: " + newValue); } else { System.out.println("The key " + keyToFind + " was not found in the YAML content."); } return yamlContent; } public static String keyToRegex(String key) { String[] parts = key.split("\\."); StringBuilder regexBuilder = new StringBuilder(); for (String part : parts) { regexBuilder.append("\\b").append(part).append("\\b\\s*:"); // Match the key and following colon if (!part.equals(parts[parts.length - 1])) { regexBuilder.append("\\s*\\n\\s*"); // Add newline and indentation for all parts except the last one } } return regexBuilder.toString(); } private static String buildRegexForKey(String key) { String[] parts = key.split("\\."); StringBuilder regexBuilder = new StringBuilder(); // 匹配每個部分的鍵和冒號,考慮到YAML的縮進 for (String part : parts) { if (regexBuilder.length() > 0) { // 如果不是第一個部分,添加縮進匹配(兩個空格) regexBuilder.append("\\n\\s*"); } regexBuilder.append("\\b").append(part).append(":\\s*"); } regexBuilder.append("[^\\s\\n]+"); // 匹配值直到下一個空白字符或換行符 return regexBuilder.toString(); } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章