apollo不重启服务自动更新配置的源码实现

@Configuration
@EnableApolloConfig
@ConditionalOnProperty(value = "apollo.bootstrap.enabled", havingValue = "true", matchIfMissing = true)
public class ApolloConfig {

    Logger logger = LoggerFactory.getLogger(ConfigChangeService.class);

    /**
     * 检测配置变化
     *
     * @param changeEvent
     */
    @ApolloConfigChangeListener
    public void configChangeListener(ConfigChangeEvent changeEvent) {
        //配置变化处理
        LinkedList<ConfigChangeService> configChangeServices = ConfigChangeServiceChain.configChangeServices;
        if (configChangeServices == null || configChangeServices.size() == 0) {
            for (String key : changeEvent.changedKeys()) {
                ConfigChange change = changeEvent.getChange(key);
                logger.info("发现变化 - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
            }
        } else {
            for (ConfigChangeService configChangeService : configChangeServices) {
                configChangeService.detectConfigChanges(changeEvent);
            }
        }
    }

    @Bean
    public ConfigChangeServiceChain configChangeServiceChain(){
        return new ConfigChangeServiceChain();
    }
}

如果我们想自定义更新配置,就实现ConfigChangeService可以根据我们自己的需求实现更新那些配置

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.e6yun.project.apollo.config.ConfigChangeService;
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.stereotype.Component;


public class ConfigChangeServiceImpl implements ConfigChangeService, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void detectConfigChanges(ConfigChangeEvent changeEvent) {
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
        }
        
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

    }

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

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guyuweilove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值