SpringBoot Apollo客户端监听配置变化、动态刷新

@Value,动态刷新
@ConfigurationProperties,需要添加apollo配置监听器@ApolloConfigChangeListener实现动态刷新

配置

pom.xml

<dependency>
    <groupId>com.ctrip.framework.apollo</groupId>
    <artifactId>apollo-client</artifactId>
    <version>1.6.0</version>
</dependency>

application.yml

app:
  id: 5ff576fef194fa22505f4331
apollo:
  cluster: default
  meta: http://dev.apollo.appblog.cn:8080,http://dev.apollo.appblog.cn:8081
  cacheDir: /opt/app/data
  bootstrap:
    enabled: true
    eagerLoad:
      enabled: true
    namespaces: application,.mysql-config

@EnableApolloConfig

@EnableApolloConfig不一定要加在启动类上,加在被Spring管理的类上即可

属性映射

@Value:直接属性映射

@Value,动态刷新

@Value("${user.userName}")
private String userName;

@ConfigurationProperties:bean属性映射

@ConfigurationProperties,需要添加apollo配置监听器@ApolloConfigChangeListener实现动态刷新

@ApolloConfigChangeListener():默认监听的是application命名空间
@ApolloConfigChangeListener("mysql-config"):指定mysql-config命名空间
@ApolloConfigChangeListener("${apollo.bootstrap.namespaces}"):指定参数所配置的命名空间(多个用逗号分隔)
import com.ctrip.framework.apollo.model.ConfigChange;
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;

/**
 * 自动刷新 ConfigurationProperties 标注的类属性
 */
@Slf4j
@Component
public class ApolloConfigChanged implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    RefreshScope refreshScope;

    /**
     * 刷新的namespace的名字:devGroup.coupon.application
     * apollo自定义的几个namespace:{@link com.ctrip.framework.apollo.core.ConfigConsts}
     * 已重写不需要配置value,默认所有的namespaces
     *
     * @param changeEvent
     */
    @ApolloConfigChangeListener("${apollo.bootstrap.namespaces}")
    private void someChangeHandler(ConfigChangeEvent changeEvent) {
        log.info("================Apollo 自动刷新值 开始 ===========================");

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

            ConfigChange configChange = changeEvent.getChange(changedKey);
            String oldValue = configChange.getOldValue();
            String newValue = configChange.getNewValue();
            log.info("[changedKey:{},oldValue={}, newValue:{}]", changedKey, oldValue, newValue);
        }

        refreshProperties(changeEvent);

        log.info("================Apollo 自动刷新值 结束 ===========================");
    }

    public void refreshProperties(ConfigChangeEvent changeEvent) {
        // 更新相应的bean的属性值,主要是存在@ConfigurationProperties注解的bean
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        refreshScope.refreshAll();
    }

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

也可以用下面这种方式:

Config config = ConfigService.getAppConfig();
config.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
            System.out.println(String.format(
                "Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s",
                change.getPropertyName(), change.getOldValue(),
                change.getNewValue(), change.getChangeType()));
        }
    }
});

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/02/spring-boot-apollo-client-monitoring-configuration-changes-and-dynamic-refreshing/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
SpringBoot Apollo客户端监听配置变化、动态刷新
@Value,动态刷新 @ConfigurationProperties,需要添加apollo配置监听器@ApolloConfigChangeListener实现动态刷新 配置 pom.xml <dependency> &l……
<<上一篇
下一篇>>
文章目录
关闭
目 录