哎,上线又出问题了!
烦人的测试环境配置和生产环境配置相差一个值,结果上线失败。惨!真惨!
为了让以后少出这个问题,亲手撸了一段代码用于比较两个环境的配置,杜绝以后这种问题再出现!
代码放在最后了哈。如果看官想自己玩一玩的话,记得引入相关依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.29</version>
</dependency>
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.*;
public class YmlCompareUtil {
public static void main(String[] args) {
String filePath2 = "application.yml";
String filePath1 = "application-prod.yml";
getYmlContent(filePath1, filePath2);
}
public static void getYmlContent(String filePath1, String filePath2) {
// 解析文件成yaml 文件
Map<String, Object> yamlMap1 = getYamlMap(filePath1);
Map<String, Object> yamlMap2 = getYamlMap(filePath2);
// 拿到yaml 文件的key 放入map1、map2 中
Map<String, Object> map1 = new HashMap<>();
getFlatMap(yamlMap1, map1,"");
Map<String, Object> map2 = new HashMap<>();
getFlatMap(yamlMap2, map2, "");
// 比较map1、map2 的key 是否一致
// map1中有,但是map2 中没有
List<String> map1Keys = new ArrayList<>();
map1.forEach((k, v) -> {
if (!map2.containsKey(k)) {
map1Keys.add(k);
}
});
map1Keys.forEach(k -> {
System.out.println("map1 中有,map2 中没有:" + k);
});
// map2中有,但是map1 中没有
List<String> map2Keys = new ArrayList<>();
map2.forEach((k, v) -> {
if (!map1.containsKey(k)) {
map2Keys.add(k);
}
});
map2Keys.forEach(k -> {
System.out.println( "map2 中有,map1 中没有:" + k);
});
// 比较map1、map2 的value 是否一致
map1.forEach((k, v) -> {
if (map2.containsKey(k)) {
if (!map2.get(k).equals(v)) {
System.out.println( "map1 中有,map2 中也有,但是值不一致:" + k);
}
}
});
}
private static Map<String, Object> getYamlMap(String filePath) {
// 读取 YML 文件
InputStream inputStream = YmlCompareUtil.class
.getClassLoader()
.getResourceAsStream(filePath);
// 创建 Yaml 对象
Yaml yaml = new Yaml();
// 解析 YML 文件为 Map 对象
Map<String, Object> data = yaml.load(inputStream);
return data;
}
private static void getFlatMap(Map<String, Object> yamlMap, Map<String, Object> resultMap, String parentKey) {
// 将map value 是map 的key 放入map 中,上级key用. 拼接
if (CollectionUtils.isEmpty(yamlMap)) {
return;
}
Set<Map.Entry<String, Object>> entries = yamlMap.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
String newKey = StringUtils.isBlank(parentKey) ? key : parentKey + "." + key;
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
getFlatMap(map, resultMap, newKey);
} else {
resultMap.put(newKey, value);
}
}
}
}


被折叠的 条评论
为什么被折叠?



