1. 背景
在实际项目中,Spring Boot项目结合使用Apollo配置中心时,经常会遇到需要更新Apollo上的项目的一些配置,比如测试环境或生产环境中,需要修改某个类的属性值,如果我们在Apollo上更新了配置,已经在运行的Spring Boot项目里默认是不生效的。为了避免重启项目才能生效,需要对Apollo配置更新进行监听,并进行一些处理,达到配置动态更新并生效。
2. 代码
maven依赖引入
<!-- Apollo配置中心 --><dependency><groupId>com.ctrip.framework.apollo</groupId><artifactId>apollo-client</artifactId><version>1.4.0</version></dependency><!-- 监听apollo配置, 实时刷新 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-context</artifactId><version>3.1.7</version></dependency>
监听类实现
java">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;}
}