分布式apollo简介
Apollo(阿波罗)是携程框架部门研发的开源配置管理中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。
本文主要介绍如何使用apollo与springboot实现动态刷新配置,如果之前不了解apollo可以查看如下文档
学习了解一下apollo,再来查看本文
正文
apollo与spring实现动态刷新配置本文主要演示2种刷新,一种基于普通字段刷新、一种基于bean上使用了@ConfigurationProperties刷新
1、普通字段刷新
a、pom.xml配置
com.ctrip.framework.apollo
apollo-client
1.6.0
b、客户端配置AppId,Apollo Meta Server
此配置有多种方法,本示例直接在application.yml配置,配置内容如下
app:
id: ${spring.application.name}
apollo:
meta: http://192.168.88.128:8080,http://192.168.88.129:8080
bootstrap:
enabled: true
eagerLoad:
enabled: true
c、项目中启动类上加上@EnableApolloConfig注解,形如下
@SpringBootApplication
@EnableApolloConfig(value = {"application","user.properties","product.properties","order.properties"})
public class ApolloApplication {
public static void main(String[] args) {
SpringApplication.run(ApolloApplication.class, args);
}
}
==@EnableApolloConfig不一定要加在启动类上,加在被spring管理的类上即可==
d、在需刷新的字段上配置@Value注解,形如
@Value("${hello}")
private String hello;
通过以上三步就可以实现普通字段的动态刷新
2.bean使用@ConfigurationProperties动态刷新
bean使用@ConfigurationProperties注解目前还不支持自动刷新,得编写一定的代码实现刷新。目前官方提供2种刷新方案
基于RefreshScope实现刷新
基于EnvironmentChangeEvent实现刷新
本文再提供一种,当bean上如果使用了@ConditionalOnProperty如何实现刷新
a、基于RefreshScope实现刷新
1、pom.xml要额外引入
org.springframework.cloud
spring-cloud-context
2.0.3.RELEASE
2、bean上使用@RefreshScope注解
@Component
@ConfigurationProperties(prefix = "product")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@RefreshScope
public class Product {
private Long id;
private String productName;
private BigDecimal price;
}
3、利用RefreshScope搭配@ApolloConfigChangeListener监听实现bean的动态刷新,其代码实现如下
@ApolloConfigChangeListener(value="product.properties",interestedKeyPrefixes = {"product."})
private void refresh(ConfigChangeEvent changeEvent){
refreshScope.refresh("product");
PrintChangeKeyUtils.printChange(changeEvent);
}
b、基于EnvironmentChangeEvent实现刷新
利用spring的事件驱动配合@ApolloConfigChangeListener监听实现bean的动态刷新,其代码如下
@Component
@Slf4j
public class UserPropertiesRefresh implements ApplicationContextAware {
private ApplicationContext applicationContext;
@ApolloConfigChangeListener(value="user.properties",interestedKeyPrefixes = {"user."})
private void refresh(ConfigChangeEvent changeEvent){
applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
PrintChangeKeyUtils.printChange(changeEvent);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationCo