前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot 中 @ConfigurationProperties 配置后 apollo 自动刷新

SpringBoot 中 @ConfigurationProperties 配置后 apollo 自动刷新

作者头像
qubianzhong
发布2019-11-21 19:54:45
4K0
发布2019-11-21 19:54:45
举报
文章被收录于专栏:行者常至行者常至

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/qwdafedv/article/details/103117320

1、在配置文件(如:application.properties)中,开启Apollo的自动更新

代码语言:javascript
复制
spring.boot.enableautoconfiguration=true

2.实现ApplicationContextAware

代码语言:javascript
复制
package com.qbz.test.commons.web.config;


import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * apollo 自动刷新
 *
 * @author qubianzhong
 * @Date 20:32 2019/11/11
 */
@Component
@Slf4j
public class ApolloRefreshConfig implements ApplicationContextAware {

    ApplicationContext applicationContext;

    @Autowired
    RefreshScope refreshScope;

	//这里指定Apollo的namespace,非常重要,如果不指定,默认只使用application
    @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION,"business","everything"})
    public void onChange(ConfigChangeEvent changeEvent) {
        for (String changedKey : changeEvent.changedKeys()) {
            log.info("apollo changed namespace:{} Key:{} value:{}", changeEvent.getNamespace(), changedKey, changeEvent.getChange(changedKey));
        }
        refreshProperties(changeEvent);
    }

    public void refreshProperties(ConfigChangeEvent changeEvent) {
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        refreshScope.refreshAll();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、在配置文件(如:application.properties)中,开启Apollo的自动更新
  • 2.实现ApplicationContextAware
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档