再不重启的情况更新配置属性,是配置中心的目的。在小的项目上面如果没有条件构建apollo这种大型的配置中心集群。那么spring cloud config无疑是一种不错的选择。那么spring cloud config提供了2种刷新方式
1:config server端刷新(全局刷新)
首先在服务端暴露出相应的刷新接口:
#暴露刷新接口
management:
endpoints:
web:
exposure:
include: bus-refresh
调用刷新接口
http://localhost:9002/actuator/bus-refresh
这个刷新会对所有的客户端都生效,如果只想刷新单个应用肯定是不合适的。
2:config client端刷新(局部刷新,指定条件刷新)
针对单个应用刷新的话,可以使用局部刷新的方法。同样的需要先暴露刷新接口
#暴露刷新接口
management:
endpoints:
web:
exposure:
include: bus-refresh
调取响应服务的刷新方法
http://ip:端口/actuator/bus-refresh
则可以指定服务刷新了,但是这种刷新是存在一定的问题的,如果是集群部署的时候,我们可能需要进行灰度发布。可以指定ApplicationContextId进行刷新
http://localhost:9002/actuator/bus-refresh?destination=user-center:9003
这里解释下ApplicationContextId:
在org.springframework.boot.context.ContextIdApplicationContextInitializer类中有如下代码:
private String getApplicationId(ConfigurableEnvironment environment) {
String name = environment.resolvePlaceholders(this.name);
String index = environment.resolvePlaceholders("${vcap.application.instance_index:${spring.application.index:${server.port:${PORT:null}}}}");
String profiles = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
if (StringUtils.hasText(profiles)) {
name = name + ":" + profiles;
}
if (!"null".equals(index)) {
name = name + ":" + index;
}
return name;
}
可以看出ApplicationContextId其实是由name:profiles:index组成的,其中name的表达式为${spring.application.name:${vcap.application.name:${spring.config.name:application}}},该表达式的意思是,如果spring.application.name参数有值则使用,后面的不再匹配;如果没有值,则继续匹配后面的,以此类推。index的表达式为${vcap.application.instance_index:${spring.application.index:${server.port:${PORT:null}}}},同理,可知如果没有配置其他配置项,那么默认的是server.port,因此一般来说,默认返回的是${spring.application.name}:${server.port}
在上面提到,可以利用不同机器ip不同的特点进行灰度发布改造,那么可以对优于server.port匹配的sping.application.index参数进行配置,所有实例都添加:sping.application.index=${spring.cloud.client.ipAddress}:${server.port}配置,那么组成的ApplicationContextId就是${spring.application.name}:${spring.application.index},即应用名称:实例ip:实例port,这种方式不仅适用于场景
http://localhost:9002/actuator/bus-refresh?destination=user-center:IP:9003