ApolloRefresherConfiguration.java 2.7 KB
Newer Older
钱坤's avatar
钱坤 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package com.tanpu.feo.feojob.config;

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 com.tanpu.common.constant.CommonConstant;
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 org.springframework.stereotype.Component;

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

/*动态刷新日志参数配置和tanpu.开头的配置*/
@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."或"tanpu."开头的配置  )
钱坤's avatar
钱坤 committed
42
	@ApolloConfigChangeListener(value = {"application.yml" }, interestedKeyPrefixes = { "logging.level.",
钱坤's avatar
钱坤 committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
			"tanpu." })
	public void onChangeLogLevel(ConfigChangeEvent changeEvent) {
		log.info("Refreshing logging levels and tanpu.");
		Iterator<String> iterator = changeEvent.changedKeys().iterator();
		while(iterator.hasNext()) {
			log.info("refresh key:{}",iterator.next());
		}
		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");
		Iterator<String> iterator = changedKeys.iterator();
		while(iterator.hasNext()) {
			log.info("refresh key:{}",iterator.next());
		}
		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;
	}
}