SpringBoot動(dòng)態(tài)更新yml文件
前言
在系統(tǒng)運(yùn)行過程中,可能由于一些配置項(xiàng)的簡單變動(dòng)需要重新打包啟停項(xiàng)目,這對(duì)于在運(yùn)行中的項(xiàng)目會(huì)造成數(shù)據(jù)丟失,客戶操作無響應(yīng)等情況發(fā)生,針對(duì)這類情況對(duì)開發(fā)框架進(jìn)行升級(jí)提供yml文件實(shí)時(shí)修改更新功能
項(xiàng)目依賴
項(xiàng)目基于的是2.0.0.RELEASE版本,所以snakeyaml需要單獨(dú)引入,高版本已包含在內(nèi)
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
網(wǎng)上大多數(shù)方法是引入spring-cloud-context配置組件調(diào)用ContextRefresher的refresh方法達(dá)到同樣的效果,考慮以下兩點(diǎn)未使用
- 開發(fā)框架使用了logback日志,引入spring-cloud-context會(huì)造成日志配置讀取錯(cuò)誤
- 引入spring-cloud-context會(huì)同時(shí)引入spring-boot-starter-actuator組件,會(huì)開放一些健康檢查路由及端口,需要對(duì)框架安全方面進(jìn)行額外控制
YML文件內(nèi)容獲取
讀取resource文件下的文件需要使用ClassPathResource獲取InputStream
public String getTotalYamlFileContent() throws Exception {
String fileName = "application.yml";
return getYamlFileContent(fileName);
}
public String getYamlFileContent(String fileName) throws Exception {
ClassPathResource classPathResource = new ClassPathResource(fileName);
return onvertStreamToString(classPathResource.getInputStream());
}
public static String convertStreamToString(InputStream inputStream) throws Exception{
return IOUtils.toString(inputStream, "utf-8");
}
YML文件內(nèi)容更新
我們獲取到y(tǒng)ml文件內(nèi)容后可視化顯示到前臺(tái)進(jìn)行展示修改,將修改后的內(nèi)容通過yaml.load方法轉(zhuǎn)換成Map結(jié)構(gòu),再使用yaml.dumpAsMap轉(zhuǎn)換為流寫入到文件
public void updateTotalYamlFileContent(String content) throws Exception {
String fileName = "application.yml";
updateYamlFileContent(fileName, content);
}
public void updateYamlFileContent(String fileName, String content) throws Exception {
Yaml template = new Yaml();
Map<String, Object> yamlMap = template.load(content);
ClassPathResource classPathResource = new ClassPathResource(fileName);
Yaml yaml = new Yaml();
//字符輸出
FileWriter fileWriter = new FileWriter(classPathResource.getFile());
//用yaml方法把map結(jié)構(gòu)格式化為yaml文件結(jié)構(gòu)
fileWriter.write(yaml.dumpAsMap(yamlMap));
//刷新
fileWriter.flush();
//關(guān)閉流
fileWriter.close();
}
YML屬性刷新
yml屬性在程序中讀取使用一般有三種
使用Value注解
@Value("${system.systemName}")
private String systemName;
通過enviroment注入讀取
@Autowired
private Environment environment;
environment.getProperty("system.systemName")
使用ConfigurationProperties注解讀取
@Component
@ConfigurationProperties(prefix = "system")
public class SystemConfig {
private String systemName;
}
Property刷新
我們通過environment.getProperty方法讀取的配置集合實(shí)際是存儲(chǔ)在PropertySources中的,我們只需要把鍵值對(duì)全部取出存儲(chǔ)在propertyMap中,將更新后的yml文件內(nèi)容轉(zhuǎn)換成相同格式的ymlMap,兩個(gè)Map進(jìn)行合并,調(diào)用PropertySources的replace方法進(jìn)行整體替換即可
但是yaml.load后的ymlMap和PropertySources取出的propertyMap兩者數(shù)據(jù)解構(gòu)是不同的,需要進(jìn)行手動(dòng)轉(zhuǎn)換
propertyMap集合就是單純的key,value鍵值對(duì),key是properties形式的名稱,例如system.systemName=>xxxxx集團(tuán)管理系統(tǒng)
ymlMap集合是key,LinkedHashMap的嵌套層次結(jié)構(gòu),例如system=>(systemName=>xxxxx集團(tuán)管理系統(tǒng))
轉(zhuǎn)換方法如下
public HashMap<String, Object> convertYmlMapToPropertyMap(Map<String, Object> yamlMap) {
HashMap<String, Object> propertyMap = new HashMap<String, Object>();
for (String key : yamlMap.keySet()) {
String keyName = key;
Object value = yamlMap.get(key);
if (value != null && value.getClass() == LinkedHashMap.class) {
convertYmlMapToPropertyMapSub(keyName, ((LinkedHashMap<String, Object>) value), propertyMap);
} else {
propertyMap.put(keyName, value);
}
}
return propertyMap;
}
private void convertYmlMapToPropertyMapSub(String keyName, LinkedHashMap<String, Object> submMap, Map<String, Object> propertyMap) {
for (String key : submMap.keySet()) {
String newKey = keyName + "." + key;
Object value = submMap.get(key);
if (value != null && value.getClass() == LinkedHashMap.class) {
convertYmlMapToPropertyMapSub(newKey, ((LinkedHashMap<String, Object>) value), propertyMap);
} else {
propertyMap.put(newKey, value);
}
}
}
刷新方法如下
String name = "applicationConfig: [classpath:/" + fileName + "]";
MapPropertySource propertySource = (MapPropertySource) environment.getPropertySources().get(name);
Map<String, Object> source = propertySource.getSource();
Map<String, Object> map = new HashMap<>(source.size());
map.putAll(source);
Map<String, Object> propertyMap = convertYmlMapToPropertyMap(yamlMap);
for (String key : propertyMap.keySet()) {
Object value = propertyMap.get(key);
map.put(key, value);
}
environment.getPropertySources().replace(name, new MapPropertySource(name, map));注解刷新
不論是Value注解還是ConfigurationProperties注解,實(shí)際都是通過注入Bean對(duì)象的屬性方法使用的,我們先自定注解RefreshValue來修飾屬性所在Bean的class
通過實(shí)現(xiàn)InstantiationAwareBeanPostProcessorAdapter接口在系統(tǒng)啟動(dòng)時(shí)過濾篩選對(duì)應(yīng)的Bean存儲(chǔ)下來,在更新yml文件時(shí)通過spring的event通知更新對(duì)應(yīng)
bean的屬性即可
注冊(cè)事件使用EventListener注解
@EventListener
public void updateConfig(ConfigUpdateEvent configUpdateEvent) {
if(mapper.containsKey(configUpdateEvent.key)){
List<FieldPair> fieldPairList = mapper.get(configUpdateEvent.key);
if(fieldPairList.size()>0){
for (FieldPair fieldPair:fieldPairList) {
fieldPair.updateValue(environment);
}
}
}
}
通知觸發(fā)事件使用ApplicationContext的publishEvent方法
@Autowired
private ApplicationContext applicationContext;
for (String key : propertyMap.keySet()) {
applicationContext.publishEvent(new YamlConfigRefreshPostProcessor.ConfigUpdateEvent(this, key));
}
YamlConfigRefreshPostProcessor的完整代碼如下
@Component
public class YamlConfigRefreshPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements EnvironmentAware {
private Map<String, List<FieldPair>> mapper = new HashMap<>();
private Environment environment;
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
processMetaValue(bean);
return super.postProcessAfterInstantiation(bean, beanName);
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
private void processMetaValue(Object bean) {
Class clz = bean.getClass();
if (!clz.isAnnotationPresent(RefreshValue.class)) {
return;
}
if (clz.isAnnotationPresent(ConfigurationProperties.class)) {
//@ConfigurationProperties注解
ConfigurationProperties config = (ConfigurationProperties) clz.getAnnotation(ConfigurationProperties.class);
for (Field field : clz.getDeclaredFields()) {
String key = config.prefix() + "." + field.getName();
if(mapper.containsKey(key)){
mapper.get(key).add(new FieldPair(bean, field, key));
}else{
List<FieldPair> fieldPairList = new ArrayList<>();
fieldPairList.add(new FieldPair(bean, field, key));
mapper.put(key, fieldPairList);
}
}
} else {
//@Valuez注解
try {
for (Field field : clz.getDeclaredFields()) {
if (field.isAnnotationPresent(Value.class)) {
Value val = field.getAnnotation(Value.class);
String key = val.value().replace("${", "").replace("}", "");
if(mapper.containsKey(key)){
mapper.get(key).add(new FieldPair(bean, field, key));
}else{
List<FieldPair> fieldPairList = new ArrayList<>();
fieldPairList.add(new FieldPair(bean, field, key));
mapper.put(key, fieldPairList);
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
public static class FieldPair {
private static PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}",
":", true);
private Object bean;
private Field field;
private String value;
public FieldPair(Object bean, Field field, String value) {
this.bean = bean;
this.field = field;
this.value = value;
}
public void updateValue(Environment environment) {
boolean access = field.isAccessible();
if (!access) {
field.setAccessible(true);
}
try {
if (field.getType() == String.class) {
String updateVal = environment.getProperty(value);
field.set(bean, updateVal);
}
else if (field.getType() == Integer.class) {
Integer updateVal = environment.getProperty(value,Integer.class);
field.set(bean, updateVal);
}
else if (field.getType() == int.class) {
int updateVal = environment.getProperty(value,int.class);
field.set(bean, updateVal);
}
else if (field.getType() == Boolean.class) {
Boolean updateVal = environment.getProperty(value,Boolean.class);
field.set(bean, updateVal);
}
else if (field.getType() == boolean.class) {
boolean updateVal = environment.getProperty(value,boolean.class);
field.set(bean, updateVal);
}
else {
String updateVal = environment.getProperty(value);
field.set(bean, JSONObject.parseObject(updateVal, field.getType()));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
field.setAccessible(access);
}
public Object getBean() {
return bean;
}
public void setBean(Object bean) {
this.bean = bean;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static class ConfigUpdateEvent extends ApplicationEvent {
String key;
public ConfigUpdateEvent(Object source, String key) {
super(source);
this.key = key;
}
}
@EventListener
public void updateConfig(ConfigUpdateEvent configUpdateEvent) {
if(mapper.containsKey(configUpdateEvent.key)){
List<FieldPair> fieldPairList = mapper.get(configUpdateEvent.key);
if(fieldPairList.size()>0){
for (FieldPair fieldPair:fieldPairList) {
fieldPair.updateValue(environment);
}
}
}
}
}到此這篇關(guān)于SpringBoot動(dòng)態(tài)更新yml文件的文章就介紹到這了,更多相關(guān)SpringBoot更新yml內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于IDEA無法預(yù)覽Markdown文件的解決思路
在IntelliJ IDEA中,有時(shí)Markdown文件無法預(yù)覽可能是因?yàn)槲募P(guān)聯(lián)設(shè)置不正確或配置信息錯(cuò)誤,首先,檢查IDE的File Types設(shè)置,確保.md和.markdown后綴已正確注冊(cè),其次,對(duì)照官方配置信息,調(diào)整Markdown設(shè)置2024-09-09
Red?Hat?安裝JDK與IntelliJ?IDEA的詳細(xì)過程
YUM是基于Red Hat的Linux發(fā)行版的一個(gè)強(qiáng)大而用戶友好的包管理工具,這篇文章主要介紹了Red?Hat安裝JDK與IntelliJ IDEA,需要的朋友可以參考下2023-08-08
SpringBoot同時(shí)啟動(dòng)不同端口圖示解析

