html5绿色的房地产手机网站模板源码,汽车网站,广州美快软件开发有限公司,wordpress 乱版1. 背景
在实际项目中#xff0c;Spring Boot项目结合使用Apollo配置中心时#xff0c;经常会遇到需要更新Apollo上的项目的一些配置#xff0c;比如测试环境或生产环境中#xff0c;需要修改某个类的属性值#xff0c;如果我们在Apollo上更新了配置#xff0c;已经在运…1. 背景
在实际项目中Spring Boot项目结合使用Apollo配置中心时经常会遇到需要更新Apollo上的项目的一些配置比如测试环境或生产环境中需要修改某个类的属性值如果我们在Apollo上更新了配置已经在运行的Spring Boot项目里默认是不生效的。为了避免重启项目才能生效需要对Apollo配置更新进行监听并进行一些处理达到配置动态更新并生效。
2. 代码
maven依赖引入 !-- Apollo配置中心 --dependencygroupIdcom.ctrip.framework.apollo/groupIdartifactIdapollo-client/artifactIdversion1.4.0/version/dependency!-- 监听apollo配置, 实时刷新 --dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-context/artifactIdversion3.1.7/version/dependency监听类实现
package com.zsx.listener;import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;/**** description: 监听apollo配置, 实时刷新* author: zsx* date: 2024/6/12 10:56*/
Configuration
public class ApolloConfigListener implements ApplicationContextAware {/*** 日志*/private static final Logger LOGGER LoggerFactory.getLogger(ApolloConfigListener.class);private ApplicationContext applicationContext;/*** 配置监听* ApolloConfigChangeListener value 属性默认 命名空间 application** 示例 ApolloConfigChangeListener(value {application, test_space})*/ApolloConfigChangeListener(value {application, application-comm, application-dao, common-redis})private void onChange(ConfigChangeEvent changeEvent) {for (String key : changeEvent.changedKeys()) {LOGGER.info(apollo key {} refresh, key);}// 更新相应的bean的属性值主要是存在ConfigurationProperties注解的beanthis.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));}Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext applicationContext;}
}