apollo动态刷新ConfigurationProperties注解标注的配置类方式

 更新时间:2025年12月02日 09:25:53   作者:一只猪啊啊  
文章介绍了在Spring Boot中使用Apollo动态刷新ConfigurationProperties注解标注的配置类时遇到的问题,以及官方推荐的两种解决方案:@RefreshScope和通过EnvironmentChangeEvent,文章通过创建一个Apollo监听类并触发EnvironmentChangeEvent来实现配置属性的实时更新

apollo动态刷新ConfigurationProperties注解标注的配置类

默认情况下 apollo无法刷新 ConfigurationProperties标注的属性实时更新

我查看官方文档他推荐了两种实现思路

@RefrashScope和通过EnvironmentChangeEvent

这两个都是在spring-cloud-context中提供的

我简单举个例子

/**
 * @Description
 * @Author changyandong
 * @Emoji (゜ - ゜)つ干杯
 * @Created Date: 2019/11/20 9:01
 * @ClassName MsGatewayProperties
 * @Version: 1.0
 */
@Component
@ConfigurationProperties("ms.gateway")
public class MsGatewayProperties {
    private MsGatewayUrlProperties url = new MsGatewayUrlProperties();

    public MsGatewayUrlProperties getUrl() {
        return url;
    }

    public void setUrl(MsGatewayUrlProperties url) {
        this.url = url;
    }
}
/**
 * @Description
 * @Author changyandong
 * @Emoji (゜ - ゜)つ干杯
 * @Created Date: 2019/11/20 9:02
 * @ClassName MsGatewayUrlProperties
 * @Version: 1.0
 */
public class MsGatewayUrlProperties {
    private String sss;
    private String xxx;

    public String getSss() {
        return sss;
    }

    public void setSss(String sss) {
        this.sss = sss;
    }

    public String getXxx() {
        return xxx;
    }

    public void setXxx(String xxx) {
        this.xxx = xxx;
    }
}

然后我创建一个apollo监听类 这里的ConfigChangeService是我们框架封装的

如果自己写的话一个普通的@ApolloConfigChangeListener类即可

/**
 * @Description
 * @Author changyandong
 * @Emoji (゜ - ゜)つ干杯
 * @Created Date: 2019/11/20 9:00
 * @ClassName MsGatewayAppolloChangeSerivce
 * @Version: 1.0
 */
@Component
public class MsGatewayApolloChangeService implements ConfigChangeService, ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(MsGatewayApolloChangeService.class);

    private ApplicationContext applicationContext;

    @Override
    public void detectConfigChanges(ConfigChangeEvent changeEvent) {
        boolean gatewayPropertiesChanged = false;

        for (String changedKey : changeEvent.changedKeys()) {

            //前缀为spring.cloud.gateway的key发生了改变(gateway的配置发生了改变)
            if (changedKey.startsWith("ms.gateway")) {
                gatewayPropertiesChanged = true;
                break;
            }
        }

        //更新gateway配置
        if (gatewayPropertiesChanged) {
            refreshGatewayProperties(changeEvent);
        }

    }

    /**
     * 更新SpringApplicationContext对象,并更新路由
     *
     * @param changeEvent
     */
    private void refreshGatewayProperties(ConfigChangeEvent changeEvent) {
        //更新配置
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
    }


    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

这时他给spring推了一个事件 EnvironmentChangeEvent

这时会触发ConfigurationPropertiesRebinder的onApplicationEvent方法进而触发rebind方法

@Component
@ManagedResource
public class ConfigurationPropertiesRebinder
  implements ApplicationContextAware, ApplicationListener<EnvironmentChangeEvent> {

 private ConfigurationPropertiesBeans beans;

 private ApplicationContext applicationContext;

 private Map<String, Exception> errors = new ConcurrentHashMap<>();

 public ConfigurationPropertiesRebinder(ConfigurationPropertiesBeans beans) {
  this.beans = beans;
 }

 @Override
 public void setApplicationContext(ApplicationContext applicationContext)
   throws BeansException {
  this.applicationContext = applicationContext;
 }

 /**
  * A map of bean name to errors when instantiating the bean.
  * @return The errors accumulated since the latest destroy.
  */
 public Map<String, Exception> getErrors() {
  return this.errors;
 }

 @ManagedOperation
 public void rebind() {
  this.errors.clear();
  // 这里会把标注了ConfigurationProperties的所有类都扫一遍
  for (String name : this.beans.getBeanNames()) {
   rebind(name);
  }
 }

 @ManagedOperation
 public boolean rebind(String name) {
  if (!this.beans.getBeanNames().contains(name)) {
   return false;
  }
  // 这里他把对象 销毁再创建  但是由于我只想刷新我自己的类 这里却把所有带ConfigurationProperties注解的都销毁重新创建 
  // 这样就很难以让我们采用这种方式
  if (this.applicationContext != null) {
   try {
    Object bean = this.applicationContext.getBean(name);
    if (AopUtils.isAopProxy(bean)) {
     bean = ProxyUtils.getTargetObject(bean);
    }
    if (bean != null) {
     this.applicationContext.getAutowireCapableBeanFactory()
       .destroyBean(bean);
     this.applicationContext.getAutowireCapableBeanFactory()
       .initializeBean(bean, name);
     return true;
    }
   }
   catch (RuntimeException e) {
    this.errors.put(name, e);
    throw e;
   }
   catch (Exception e) {
    this.errors.put(name, e);
    throw new IllegalStateException("Cannot rebind to " + name, e);
   }
  }
  return false;
 }

 @ManagedAttribute
 public Set<String> getBeanNames() {
  return new HashSet<>(this.beans.getBeanNames());
 }

 @Override
 public void onApplicationEvent(EnvironmentChangeEvent event) {
  if (this.applicationContext.equals(event.getSource())
    // Backwards compatible
    || event.getKeys().equals(event.getSource())) {
   rebind();
  }
 }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot 钩子接口的实现代码

    SpringBoot 钩子接口的实现代码

    本文主要介绍了SpringBoot 钩子接口,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • 详解Spring Boot 自定义PropertySourceLoader

    详解Spring Boot 自定义PropertySourceLoader

    这篇文章主要介绍了详解Spring Boot 自定义PropertySourceLoader,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • 教你快速搭建sona服务及idea使用sona的方法

    教你快速搭建sona服务及idea使用sona的方法

    Sonar 是一个用于代码质量管理的开放平台。通过插件机制,Sonar 可以集成不同的测试工具,代码分析工具,以及持续集成工具,本文给大家分享搭建sona服务及idea使用sona的方法,感兴趣的朋友一起看看吧
    2021-06-06
  • spring cloud gateway限流常见算法实现

    spring cloud gateway限流常见算法实现

    本文主要介绍了spring cloud gateway限流常见算法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-02-02
  • Java 数组分析及简单实例

    Java 数组分析及简单实例

    这篇文章主要介绍了Java 数组分析及简单实例的相关资料,在Java中它就是对象,一个比较特殊的对象,需要的朋友可以参考下
    2017-03-03
  • Java守护线程用法实例分析

    Java守护线程用法实例分析

    这篇文章主要介绍了Java守护线程用法,结合实例形式分析了java守护线程相关的原理、用法及相关操作注意事项,需要的朋友可以参考下
    2019-10-10
  • Java控制台实现猜拳游戏小游戏

    Java控制台实现猜拳游戏小游戏

    这篇文章主要为大家详细介绍了Java控制台实现猜拳游戏小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-11-11
  • Java带复选框的树(Java CheckBox Tree)实现和应用

    Java带复选框的树(Java CheckBox Tree)实现和应用

    这篇文章主要为大家详细介绍了Java带复选框的树实现和应用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • java数据结构实现双向链表功能

    java数据结构实现双向链表功能

    这篇文章主要为大家详细介绍了java数据结构实现双向链表功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • MyBatis typeAliases元素标签(含注解方式)及其属性、设置方式

    MyBatis typeAliases元素标签(含注解方式)及其属性、设置方式

    这篇文章主要介绍了MyBatis typeAliases元素标签(含注解方式)及其属性、设置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09

最新评论