RefreshScope
@RefreshScope(org.springframework.cloud.context.scope.refresh)是spring cloud提供的一种特殊的scope实现,用来实现配置、实例热加载。
@RefreshScope 实现流程
- 需要动态刷新的类标注@RefreshScope 注解
- @RefreshScope 注解标注了@Scope 注解,并默认了ScopedProxyMode.TARGET_CLASS; 属性,此属性的功能就是在创建一个代理,在每次调用的时候都用它来调用GenericScope get 方法来获取对象
- 如属性发生变更会调用 ContextRefresher refresh() -》RefreshScope refreshAll() 进行缓存清理方法调用,并发送刷新事件通知 -》 GenericScope 真正的 清理方法destroy() 实现清理缓存
- 在下一次使用对象的时候,会调用GenericScope get(String name, ObjectFactory<?> objectFactory) 方法创建一个新的对象,并存入缓存中,此时新对象因为Spring 的装配机制就是新的属性了。
客户端项目增加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
客户端项目修改配置文件
#显示的暴露接入点
management.endpoints.web.exposure.include=refresh,health,info
客户端程序增加支持刷新注解
@RestController
//刷新触发地址/actuator/refresh - post
@RefreshScope
public class ConfigTestController {
//配置信息通过@Value注解读取,配置项用${配置项}读取
@Value("${test.config}")
private String configTest;
@RequestMapping("/ConfigTest")
public String ConfigTest(){
return this.configTest;
}
}
ConfigurationProperties
在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值
test:
auth:
client:
id: admin
secret: admin123456
@Component
@ConfigurationProperties("test.auth.client")
@Getter
@Setter
public class AuthClientProp {
/**
* 授权id
*/
private String id;
/**
* 授权密钥
*/
private String secret;
}
启动时,id和secret会自动赋值为admin和admin123456。
通过发送post请求到http://服务ip:端口/actuator/refresh
,会触发刷新机制,从通过配置中心从git库拉取最新的数据。而不需要添加注解@RefreshScope。