赞
踩
package com.baasia.common.utils.utils; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import java.io.FileWriter; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.Map; /** * @author Yuan */ @Slf4j @Component public class YamlUtils { private final static DumperOptions OPTIONS = new DumperOptions(); static { //设置yaml读取方式为块读取 OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); OPTIONS.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); OPTIONS.setPrettyFlow(false); } /** * 将yaml配置文件转化成map * fileName 默认是resources目录下的yaml文件, 如果yaml文件在resources子目录下,需要加上子目录 比如:conf/config.yaml * * @param fileName * @return */ public Map<String, Object> getYamlToMap(String fileName) { LinkedHashMap<String, Object> yamls = new LinkedHashMap<String, Object>(); Yaml yaml = new Yaml(); try { @Cleanup InputStream in = YamlUtils.class.getClassLoader().getResourceAsStream(fileName); yamls = yaml.loadAs(in, LinkedHashMap.class); } catch (Exception e) { log.error("{} load failed !!!", fileName); } return yamls; } /** * key格式:aaa.bbb.ccc * 通过properties的方式获取yaml中的属性值 * * @param key * @param yamlMap * @return */ public Object getValue(String key, Map<String, Object> yamlMap) { String[] keys = key.split("[.]"); Object o = yamlMap.get(keys[0]); if (key.contains(".")) { if (o instanceof Map) { return getValue(key.substring(key.indexOf(".") + 1), (Map<String, Object>) o); } else { return null; } } else { return o; } } /** * 使用递归的方式设置map中的值,仅适合单一属性 * key的格式: "server.port" * server.port=111 **/ public Map<String, Object> setValue(String key, Object value) { Map<String, Object> result = new LinkedHashMap<String, Object>(); String[] keys = key.split("[.]"); int i = keys.length - 1; result.put(keys[i], value); if (i > 0) { return setValue(key.substring(0, key.lastIndexOf(".")), result); } return result; } public Map<String, Object> setValue(Map<String, Object> map, String key, Object value) { String[] keys = key.split("\\."); int len = keys.length; Map temp = map; for (int i = 0; i < len - 1; i++) { if (temp.containsKey(keys[i])) { temp = (Map) temp.get(keys[i]); } else { return null; } if (i == len - 2) { temp.put(keys[i + 1], value); } } for (int j = 0; j < len - 1; j++) { if (j == len - 1) { map.put(keys[j], temp); } } return map; } /** * 修改yaml中属性的值 * * @param key key是properties的方式: aaa.bbb.ccc (key不存在不修改) * @param value 新的属性值 (新属性值和旧属性值一样,不修改) * @param yamlName * @return true 修改成功,false 修改失败。 */ public boolean updateYaml(String key, Object value, String yamlName) { Map<String, Object> yamlToMap = this.getYamlToMap(yamlName); if (null == yamlToMap) { return false; } Object oldVal = this.getValue(key, yamlToMap); //未找到key 不修改 if (null == oldVal) { log.error("{} key is not found", key); return false; } //不是最小节点值,不修改 if (oldVal instanceof Map) { log.error("input key is not last node {}", key); return false; } //新旧值一样 不修改 if (value.equals(oldVal)) { log.info("newVal equals oldVal, newVal: {} , oldVal: {}", value, oldVal); return false; } Yaml yaml = new Yaml(OPTIONS); String path = this.getClass().getClassLoader().getResource(yamlName).getPath(); try { Map<String, Object> resultMap = this.setValue(yamlToMap, key, value); if (resultMap != null) { yaml.dump(this.setValue(yamlToMap, key, value), new FileWriter(path)); return true; } else { return false; } } catch (Exception e) { log.error("yaml file update failed !"); log.error("msg : {} ", e.getMessage()); log.error("cause : {} ", e.getCause()); } return false; } /** * 修改yaml中属性的值(就算key为 null也肯定会修改) * * @param key key是properties的方式: aaa.bbb.ccc (key不存在不修改) * @param value 新的属性值 (新属性值和旧属性值一样,不修改) * @param yamlName * @return true 修改成功,false 修改失败。 */ public boolean updateYamlToNULL(String key, Object value, String yamlName) { Map<String, Object> yamlToMap = this.getYamlToMap(yamlName); if (null == yamlToMap) { return false; } Object oldVal = this.getValue(key, yamlToMap); //不是最小节点值,不修改 if (oldVal instanceof Map) { log.error("input key is not last node {}", key); return false; } Yaml yaml = new Yaml(OPTIONS); String path = this.getClass().getClassLoader().getResource(yamlName).getPath(); try { Map<String, Object> resultMap = this.setValue(yamlToMap, key, value); if (resultMap != null) { yaml.dump(this.setValue(yamlToMap, key, value), new FileWriter(path)); return true; } else { return false; } } catch (Exception e) { log.error("yaml file update failed !"); log.error("msg : {} ", e.getMessage()); log.error("cause : {} ", e.getCause()); } return false; } public static void main(String[] args) { YamlUtils configs = new YamlUtils(); Map<String, Object> yamlToMap = configs.getYamlToMap("conf/config.yaml"); System.out.println(yamlToMap); boolean b = configs.updateYaml("sys.cpu.name", "Intel Core i7", "conf/config.yaml"); System.out.println(b); System.out.println(configs.getYamlToMap("conf/config.yaml")); } }
package com.baasia.common.utils.config.nacos; import com.baasia.common.utils.constant.AuthConstant; import com.baasia.common.utils.utils.ContextUtil; import com.baasia.common.utils.utils.YamlUtils; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.Map; @Log4j2 public class NacosConfig { //读取的文件 public static final String BOOTSTRAP_YML_URL = "bootstrap.yml"; /** * nacos 地址 */ public static final String NACOS_SERVER_ADDR = "spring.cloud.nacos.config.server-addr"; /** * nacos discovery 地址 */ public static final String NACOS_SERVER_DISCOVERY_ADDR = "spring.cloud.nacos.discovery.server-addr"; /** * 项目启动的环境 */ public static final String ACTIVE_CONFIG = "spring.profiles.active"; /** * 修改nacos 默认 * 项目初始化前先执行当前参数用于初始化class 文件中的配置 */ public void upNacosData(){ YamlUtils configs = new YamlUtils(); Map<String, Object> yamlToMap = configs.getYamlToMap(BOOTSTRAP_YML_URL); //项目启动环境参数 Object env = configs.getValue(ACTIVE_CONFIG, yamlToMap); //nacos 地址参数 Object nacos = configs.getValue(NACOS_SERVER_ADDR, yamlToMap); /** * 判断nacos 是否有值,没有则使用 */ Object bootstrapNacos = configs.getValue(NACOS_SERVER_ADDR, yamlToMap); if (null == bootstrapNacos || "".equals(bootstrapNacos)){ //参数默认读取dev nacos = AuthConstant.NACOS_DEV; env = AuthConstant.DEV; } //调用私有方法设置yaml 文件参数 setNacosUrl(configs, NACOS_SERVER_ADDR, nacos !=null?nacos.toString():null, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, env != null ? env.toString() : null); } /** * 设置nacos 地址 * @param configs * @param nacos nacos项配置位置 * @param nacosUrl nacosUrl nacos路径 * @param bootstrapYml bootstrap 文件名称 * @param activeConfig 项目启动的环境配置位置 * @param env 环境变量 */ private void setNacosUrl(YamlUtils configs, String nacos, String nacosUrl, String bootstrapYml, String activeConfig, String env) { //修改nacos boolean flag = configs.updateYamlToNULL(nacos, nacosUrl, bootstrapYml); //修改启动配置 configs.updateYamlToNULL(activeConfig, env, bootstrapYml); log.info("环境变量:" + env + "--------------->nacos地址:" + nacosUrl); } public void nacosDate() throws IOException { //springBoot 启动时将环境参数放入了ApplicationContext 中,这个工具类就是获取ApplicationContext的环境参数 String activeProfile = new ContextUtil().getActiveProfile(); YamlUtils configs = new YamlUtils(); Map<String, Object> yamlToMap = configs.getYamlToMap(BOOTSTRAP_YML_URL); System.out.println(yamlToMap); /** * 设置nacos 地址 */ if (AuthConstant.TEST.equals(activeProfile)) { setNacosUrl(configs, NACOS_SERVER_ADDR, AuthConstant.NACOS_TEST, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, AuthConstant.TEST); setNacosUrl(configs, NACOS_SERVER_DISCOVERY_ADDR, AuthConstant.NACOS_TEST, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, AuthConstant.TEST); } else if (AuthConstant.PROD.equals(activeProfile)) { setNacosUrl(configs, NACOS_SERVER_ADDR, AuthConstant.NACOS_PROD, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, AuthConstant.PROD); setNacosUrl(configs, NACOS_SERVER_DISCOVERY_ADDR, AuthConstant.NACOS_PROD, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, AuthConstant.PROD); } else { setNacosUrl(configs, NACOS_SERVER_ADDR, AuthConstant.NACOS_DEV, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, AuthConstant.DEV); setNacosUrl(configs, NACOS_SERVER_DISCOVERY_ADDR, AuthConstant.NACOS_DEV, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, AuthConstant.DEV); } Map<String, Object> yamlToMaprrrr = configs.getYamlToMap(BOOTSTRAP_YML_URL); System.out.println("更改后的nacos: " + yamlToMaprrrr.toString()); } }
2.读取nacos配置(Properties 文件)
YamlUtils configs = new YamlUtils();
Map<String, Object> yamlToMap = configs.getYamlToMap(NacosConfig.BOOTSTRAP_YML_URL);
//获取nacos地址
Object nacos = configs.getValue(NacosConfig.NACOS_SERVER_ADDR, yamlToMap);
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, nacos);
ConfigService configService = NacosFactory.createConfigService(properties);
String content = configService.getConfig("quartz.properties", "DEFAULT_GROUP", 5000);
properties.load(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
//根据key获取
properties.getProperty("xxxx")
(yml)
YamlUtils configs = new YamlUtils(); Map<String, Object> yamlToMap = configs.getYamlToMap(NacosConfig.BOOTSTRAP_YML_URL); //获取nacos地址 Object nacos = configs.getValue(NacosConfig.NACOS_SERVER_ADDR, yamlToMap); Properties properties = new Properties(); YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); //设置获取地址 properties.put(PropertyKeyConst.SERVER_ADDR, nacos); //获取全部nacos配置文件 ConfigService configService = NacosFactory.createConfigService(properties); //根据dataId 与 group 拿去对应的配置文件 String content = configService.getConfig("commonUrl.yml", "DEFAULT_GROUP", 5000); //将内容转为Resource yamlFactory.setResources(new ByteArrayResource(content.getBytes())); properties = yamlFactory.getObject(); properties.getProperty("xxxx");
有问题可留言或私信,看到即回
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。