@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;
}
}