如何在YAML中换行拆分字符串并实现指定格式?
解决YAML块样式Prometheus查询字符串的构造问题
问题描述
我有一段Java字符串定义:
private String QUERY = "| sum(increase(nginx_ingress_controller_requests{path=?}[10m]))";
想给这个字符串添加换行,让sum(...)部分单独位于|的下一行,生成符合要求的YAML格式。
尝试过的错误写法
- 拼接字符串方式:
"| " + "sum(increase(nginx_ingress_controller_requests{path=?}[10m]))"
结果出现两个|,格式不符合预期。
- 直接在字符串内换行:
private String QUERY = "| sum(increase(nginx_ingress_controller_requests{path=?}[10m]))";
输出的YAML中query字段被包裹在引号里,不是块样式格式:
query: "| sum(increase(nginx_ingress_controller_requests{path=/hi}[10m]))"
转换YAML的代码
public static List<HasMetadata> convertResourceToHashset(Object object) { KubernetesClient kubernetesClient = new DefaultKubernetesClient(); try { // Create a YAML representation of the data DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setIndicatorIndent(0); Yaml yaml = new Yaml(options); String yamlString = yaml.dumpAsMap(object); // Remove the class name tag by converting it to a map Map<String, Object> yamlMap = yaml.load(yamlString); String finalYaml = yaml.dump(yamlMap); // Convert the YAML string to an InputStream InputStream yamlStream = new ByteArrayInputStream(finalYaml.getBytes(StandardCharsets.UTF_8)); // Load the YAML InputStream into a list of HasMetadata return kubernetesClient.load(yamlStream).get(); } catch (Exception e) { System.err.println("Error in convert resource to Hashset : " + e.getMessage()); e.printStackTrace(); throw e; } }
期望的YAML格式
apiVersion: keda.sh/v1alpha1 kind: ScaledObject metadata: name: test-scale namespace: karavan spec: scaleTargetRef: kind: Deployment name: helloworld minReplicaCount: 1 maxReplicaCount: 2 cooldownPeriod: 30 pollingInterval: 1 triggers: - type: prometheus metadata: serverAddress: http://kube-prometheus-stack-prometheus.monitoring:9090 # figure out where to update the metrices metricName: nginx_ingress_controller_requests query: | sum(increase(nginx_ingress_controller_requests{path="/test"}[10m])) threshold: "10"
解决方案
1. 正确构造Java字符串
不需要手动添加|,直接定义包含换行和对应缩进的字符串:
private String QUERY = "\n sum(increase(nginx_ingress_controller_requests{path=?}[10m]))";
这里的\n实现换行,前面的两个空格对应YAML中sum字段需要的缩进量。
2. 调整SnakeYAML配置
修改DumperOptions,让SnakeYAML自动生成块样式格式:
DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setIndicatorIndent(2); // 设置|后的缩进,和YAML中的对齐一致 options.setSplitLines(true); options.setWidth(100); // 避免内容被自动截断换行
3. 优化序列化逻辑
原代码中先dump再load再dump的步骤会破坏多行字符串格式,直接序列化对象即可:
// 替换原序列化步骤 String finalYaml = yaml.dump(object);
原理说明
YAML中的|是块样式标量的标记,由SnakeYAML自动添加,无需手动写入字符串。当Java字符串包含换行时,SnakeYAML会根据配置自动使用块样式格式化,生成符合预期的YAML结构。
内容的提问来源于stack exchange,提问作者Elias Al-Swais MiddleEast
相关产品推荐
相关产品推荐

