• zp's avatar
    init · f9a4de2a
    zp authored
    f9a4de2a
ApolloRefresherConfiguration.java 2.46 KB
package com.tanpu.fund.config.apollo;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.boot.ApolloAutoConfiguration;
import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.PostConstruct;
import java.util.Set;

/*动态刷新日志参数配置*/
// @Component
@Slf4j
 @ConditionalOnProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED)
 @AutoConfigureAfter(ApolloAutoConfiguration.class)
public class ApolloRefresherConfiguration implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	@ApolloConfig
	private Config config;

	@PostConstruct
	private void initialize() {
		log.info("初始化配置变更监听");
		refresh(config.getPropertyNames());
	}

	// 刷新参数(刷新"common"和"application"空间中,"logging.level."或"aniu."开头的配置  )
	@ApolloConfigChangeListener(value = { "common", "application" }, interestedKeyPrefixes = { "logging.level.",
			"tanpu." })
	public void onChangeLogLevel(ConfigChangeEvent changeEvent) {
		log.info("Refreshing logging levels and tanpu.");
		for (String s : changeEvent.changedKeys()) {
			log.info("refresh key:{}", s);
		}
		this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
		log.info("Logging levels and tanpu. refreshed");
	}

	/** 刷新参数配置 */
	private void refresh(Set<String> changedKeys) {
		log.info("Refreshing logging.level and tanpu. properties");
		for (String changedKey : changedKeys) {
			log.info("refresh key:{}", changedKey);
		}
		this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
		log.info("logging.level properties and tanpu. refreshed");
	}

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