• 读取yaml文件的值


    记录一下,读取yaml文件中属性的值,这里用Kubernetes的deployment.yaml文件来举例。

    读取yaml文件中的image的值

    yaml文件

    1. apiVersion: apps/v1 # 1.9.0 之前的版本使用 apps/v1beta2,可通过命令 kubectl api-versions 查看
    2. kind: Deployment #指定创建资源的角色/类型
    3. metadata: #资源的元数据/属性
    4. name: nginx-deployment #资源的名字,在同一个namespace中必须唯一
    5. spec:
    6. replicas: 2 #副本数量2
    7. selector: #定义标签选择器
    8. matchLabels:
    9. app: web-server
    10. template: #这里Pod的定义
    11. metadata:
    12. labels: #Pod的label
    13. app: web-server
    14. spec: # 指定该资源的内容
    15. containers:
    16. - name: nginx #容器的名字
    17. image: nginx:1.12.1 #容器的镜像地址
    18. ports:
    19. - containerPort: 80 #容器对外的端口

    读取文件的代码:

    1. package com.zhh.demo;
    2. import com.alibaba.fastjson.JSON;
    3. import com.alibaba.fastjson.JSONArray;
    4. import com.alibaba.fastjson.JSONObject;
    5. import org.junit.jupiter.api.Test;
    6. import org.springframework.boot.test.context.SpringBootTest;
    7. import org.yaml.snakeyaml.Yaml;
    8. import java.io.File;
    9. import java.io.FileInputStream;
    10. import java.io.FileNotFoundException;
    11. import java.util.ArrayList;
    12. import java.util.List;
    13. import java.util.Map;
    14. /**
    15. * @Description: yaml文件属性读取
    16. * @Author: zhaoheng
    17. */
    18. @SpringBootTest
    19. public class YamlTest {
    20. /**
    21. * 读取yaml文件中的image标签的值,文件中可以有多个image标签,最终得到一个数组
    22. * @param yamlPath 需要读取的yaml文件路径
    23. * @return 得到一个数组
    24. * @throws FileNotFoundException
    25. */
    26. public static List getImageValues(String yamlPath) throws FileNotFoundException {
    27. List imageList = new ArrayList<>();
    28. Yaml yaml = new Yaml();
    29. Map map = yaml.load(new FileInputStream(new File(yamlPath)));
    30. // 把map对象转换成json对象,方便后续的层级读取
    31. JSONObject jsonObject = (JSONObject) JSON.toJSON(map);
    32. // 一层一层读取,同一层级可能有多个同样的标签,所以得到一个数组
    33. JSONArray jsonArray = jsonObject.getJSONObject("spec").getJSONObject("template").getJSONObject("spec").getJSONArray("containers");
    34. jsonArray.forEach(obj -> {
    35. // 获取image标签的值
    36. imageList.add(String.valueOf(((JSONObject) obj).get("image")));
    37. });
    38. return imageList;
    39. }
    40. @Test
    41. void yamlTest() throws FileNotFoundException {
    42. String path = "D:\\temp\\test.yaml";
    43. // 得到yaml文件中的image镜像的值
    44. List list = YamlTest.getImageValues(path);
    45. System.out.println(list.toString());
    46. }
    47. }

    结果展示:

  • 相关阅读:
    OpenMMLap之Hook机制详解
    R语言ggplot2可视化时间序列柱形图:通过双色渐变配色颜色主题可视化时间序列柱形图
    MAC上修改mysql的密码(每一步都图文解释哦)
    基于ssm服装购物系统
    service worker实现静态资源缓存
    CAN总线协议测试拓扑图
    ModuleNotFoundError: No module named ‘Crypto.Cipher‘或‘Crypto 的终极解决方案
    MyBatis大数据量插入方案
    win10家庭版找不到组策略gpedit.msc怎么办?
    2023 校园招聘 大疆8-7 后端笔试题总结
  • 原文地址:https://blog.csdn.net/Muscleheng/article/details/132944033