通过代码获取nacos中配置的yml或properties(静态项⽬导个nacos的包也可。
。。
1. 新建个⼯具类 YamlUtils
package com.baasiamon.utils.utils;
import lombok.Cleanup;
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= ClassLoader().getResourceAsStream(fileName);
yamls = yaml.loadAs(in, LinkedHashMap.class);
} catch (Exception e){
<("{} load failed ", fileName);
}
return yamls;
}
/
**
* key格式:
* 通过properties的⽅式获取yaml中的属性值
*
* @param key
* @param yamlMap
* @return
*/
public Object getValue(String key, Map<String, Object> yamlMap){
String[] keys = key.split("[.]");
String[] keys = key.split("[.]");
Object o = (keys[0]);
ains(".")){
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;
bootstrap项目
for(int i =0; i < len - 1; i++){
ainsKey(keys[i])){
temp =(Map) (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的⽅式: (key不存在不修改)
* @param value    新的属性值(新属性值和旧属性值⼀样,不修改)
* @param yamlName
* @return true修改成功,false 修改失败。
*/
public boolean updateYaml(String key, Object value, String yamlName){
Map<String, Object> yamlToMap = YamlToMap(yamlName);
if(null == yamlToMap){
if(null == yamlToMap){
return false;
}
Object oldVal = Value(key, yamlToMap);
//未到key 不修改
if(null == oldVal){
<("{} key is not found", key);
return false;
}
/
/不是最⼩节点值,不修改
if(oldVal instanceof Map){
<("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 = Class().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){
<("yaml file update failed !");
<("msg : {} ", e.getMessage());
<("cause : {} ", e.getCause());
}
return false;
}
/**
* 修改yaml中属性的值(就算key为 null也肯定会修改)
*
* @param key      key是properties的⽅式: (key不存在不修改)
* @param value    新的属性值(新属性值和旧属性值⼀样,不修改)
* @param yamlName
* @return true修改成功,false 修改失败。
*/
public boolean updateYamlToNULL(String key, Object value, String yamlName){
Map<String, Object> yamlToMap = YamlToMap(yamlName);
if(null == yamlToMap){
return false;
}
Object oldVal = Value(key, yamlToMap);
//不是最⼩节点值,不修改
if(oldVal instanceof Map){
<("input key is not last node {}", key);
return false;
}
Yaml yaml = new Yaml(OPTIONS);
String path = Class().getClassLoader().getResource(yamlName).getPath();        try {
Map<String, Object> resultMap = this.setValue(yamlToMap, key, value);
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){
<("yaml file update failed !");
<("msg : {} ", e.getMessage());
<("cause : {} ", e.getCause());
}
return false;
}
public static void main(String[] args){
YamlUtils configs = new YamlUtils();
Map<String, Object> yamlToMap = YamlToMap("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.YamlToMap("conf/config.yaml"));
}
}
package com.fig.nacos;
import com.stant.AuthConstant;
import com.baasiamon.utils.utils.ContextUtil;
import com.baasiamon.utils.utils.YamlUtils;
log4j.Log4j2;
import java.io.IOException;
import java.util.Map;
@Log4j2
public class NacosConfig {
//读取的⽂件
public static final String BOOTSTRAP_YML_URL ="l";
/**
* nacos 地址
*/
public static final String NACOS_SERVER_ADDR ="spring.fig.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(){
public void upNacosData(){
YamlUtils configs = new YamlUtils();
Map<String, Object> yamlToMap = YamlToMap(BOOTSTRAP_YML_URL);
//项⽬启动环境参数
Object env= Value(ACTIVE_CONFIG, yamlToMap);
//nacos 地址参数
Object nacos = Value(NACOS_SERVER_ADDR, yamlToMap);
/**
* 判断nacos 是否有值,没有则使⽤
*/
Object bootstrapNacos = Value(NACOS_SERVER_ADDR, yamlToMap);
if(null == bootstrapNacos ||"".equals(bootstrapNacos)){
/
/参数默认读取dev
nacos = AuthConstant.NACOS_DEV;
env= AuthConstant.DEV;
}
//调⽤私有⽅法设置yaml ⽂件参数
setNacosUrl(configs, NACOS_SERVER_ADDR, nacos !=String():null, BOOTSTRAP_YML_URL, ACTIVE_CONFIG, env!= null ?    String(): 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 = YamlToMap(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, AuthCon stant.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, AuthCon stant.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, AuthConst ant.DEV);
}
Map<String, Object> yamlToMaprrrr = YamlToMap(BOOTSTRAP_YML_URL);
System.out.println("更改后的nacos: " + String());
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。