博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
详解:java工具之解析yaml文件
阅读量:2338 次
发布时间:2019-05-10

本文共 2880 字,大约阅读时间需要 9 分钟。

工具使用背景

很多配置项都是使用yaml的格式进行配置的, 按一定的格式进行缩进, 一眼看上去,清晰明了.

如Springboot工程下图所示:

如:k8s的Deploy文件:

 

本次写这个yaml工具解析是想解析k8s的config文件,然后封装一个k8s客户端. 因为无论阿里云还是华为云,要查看多个容器的日志. 都不是方便.

基础依赖

这个工具是在已有的工具上进行封装的

gradle:

  •  
compile group: 'org.yaml', name: 'snakeyaml', version: '1.25'

maven:

org.yaml
snakeyaml
1.25

 

封装的代码

// 首先声明一个Map存解析之后的内容:Map
properties; // 空的构造函数 public YamlTools() {
} // 以文件路径为条件的构造函数 public YamlTools(String filePath) {
InputStream inputStream = null; try {
inputStream = new FileInputStream(filePath); } catch (FileNotFoundException e) {
e.printStackTrace(); } // 调基础工具类的方法 Yaml yaml = new Yaml(); properties = yaml.loadAs(inputStream, Map.class); } // 从String 中获取配置的方法 public void initWithString(String content) {
// 这里的yaml和上面那个应该可以抽取成一个全局变量,不过平常用的时候 // 也不会两个同时用 Yaml yaml = new Yaml(); properties = yaml.loadAs(content, Map.class); } /** * 从Map中获取配置的值 * 传的key支持两种形式, 一种是单独的,如user.path.key * 一种是获取数组中的某一个,如 user.path.key[0] * @param key * @return */ public
T getValueByKey(String key, T defaultValue) {
String separator = "."; String[] separatorKeys = null; if (key.contains(separator)) {
// 取下面配置项的情况, user.path.keys 这种 separatorKeys = key.split("\\."); } else {
// 直接取一个配置项的情况, user Object res = properties.get(key); return res == null ? defaultValue : (T) res; } // 下面肯定是取多个的情况 String finalValue = null; Object tempObject = properties; for (int i = 0; i < separatorKeys.length; i++) {
//如果是user[0].path这种情况,则按list处理 String innerKey = separatorKeys[i]; Integer index = null; if (innerKey.contains("[")) {
// 如果是user[0]的形式,则index = 0 , innerKey=user index = Integer.valueOf(StringTools.getSubstringBetweenFF(innerKey, "[", "]")[0]); innerKey = innerKey.substring(0, innerKey.indexOf("[")); } Map
mapTempObj = (Map) tempObject; Object object = mapTempObj.get(innerKey); // 如果没有对应的配置项,则返回设置的默认值 if (object == null) {
return defaultValue; } Object targetObj = object; if (index != null) {
// 如果是取的数组中的值,在这里取值 targetObj = ((ArrayList) object).get(index); } // 一次获取结束,继续获取后面的 tempObject = targetObj; if (i == separatorKeys.length - 1) {
//循环结束 return (T) targetObj; } } return null; }

 

运行效果

以上图中的K8s为例,运行如下图所示:

总结

一个小工具, 根据自己的需求封装了一下,大家也可以定制自己的工具

转载地址:http://lxrpb.baihongyu.com/

你可能感兴趣的文章
安全模块springboot security
查看>>
springcloud gateway
查看>>
drools使用记录
查看>>
阿里六面,挂在hrg,我真的不甘心!
查看>>
人生的康波周期,把握住一次,足以改变命运!
查看>>
互联网公司那些价值观-阿里巴巴
查看>>
去面试快手,问了我很多消息队列的知识!
查看>>
图解LeetCode No.18之四数之和
查看>>
402. Remove K Digits
查看>>
75. Sort Colors
查看>>
获取数组中前K小的数字
查看>>
数组heapify变为堆结构
查看>>
二叉树的非递归遍历
查看>>
218. The Skyline Problem
查看>>
Java PAT (Basic Level) Practice 写出这个数
查看>>
Python PAT (Basic Level) Practice 1016 部分A+B
查看>>
Python PAT (Basic Level) Practice 1006 换个格式输出整数
查看>>
Python PAT (Basic Level) Practice 1009 说反话
查看>>
Python PAT (Basic Level) Practice 1011 A+B 和 C
查看>>
Python PAT (Basic Level) Practice 1017 A除以B
查看>>