假设你接到一个需求,比如从阿里云上拉取数据,当产品需要上传一份新数据后,你需要拉到最新的数据做解析,就可以使用监听Apollo的方式,来监听数据的变化。比较初级,不做过多解释了。
使用 @EnableApolloConfig 注解后就可以通过 @Value 来获取配置信息;
1. 监听Apollo其实很简单,所需注解
@EnableApolloConfig // 通常加在启动类上
@ApolloConfigChangeListener
@Component // 或者@Service都可
2. 实例
@Slf4j
@Service
public class AliyunOssService {
@Value("${alioss.object-name}")
private String objectName;
@ApolloConfigChangeListener
private void someChangeHandler(ConfigChangeEvent changeEvent) {
if (changeEvent.isChanged("alioss.object-name")) {
// 监听到该配置变化,要做什么
}
}
private void dynamicConfigs() {
Config config = ConfigService.getAppConfig();
config.addChangeListener(changeEvent -> {
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
log.info("DynamicConfigs found change - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(), change.getOldValue(),
change.getNewValue(), change.getChangeType());
}
});
}
}