实现自动刷新 config server 是不需要修改的,去 config client 真正的微服务那边去修改
A Spring
@Bean
that is marked as@RefreshScope
will get special treatment when there is a configuration change. This addresses the problem of stateful beans that only get their configuration injected when they are initialized.当配置发生修改的时候,用
@RefreshScope标注的springbean它会得到特殊处理。
For instance if a
DataSource
has open connections when the database URL is changed via theEnvironment
, we probably want the holders of those connections to be able to complete what they are doing. Then the next time someone borrows a connection from the pool he gets one with the new URL.举例子:datasource的url发上了改变,这个东西可能正在使用,当前使用的还依旧执行,然后下一次你那的就是新的配置内容。
用了这个注解,就可以不用担心中断,原先的配置按照原先的走完,新的会按照新的走!!
- bootstrap.yml
spring:
application:
name: foobar
cloud:
config:
uri: http://user:password123@localhost:8080 # 仅仅增加部分“user:password123”
profile: dev
label: master # 当configserver的后端存储是Git时,默认是master
- application.yml
server:
port: 8081
- 加注解ConfigClientController添加@RefreshScope
@RestController
@RefreshScope
public class ConfigClientController {
@Value("${profile}")
private String profile;
@GetMapping("/profile")
public String getProfile() {
return profile;
}
}
- 添加依赖spring-boot-starter-actuator
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
- 小测试——启动 config server ,再启动 config client,访问localhost:8080/profile,返回结果如下
如果在Git仓库将profile的值修改,foobar-dev.yml,叫做refresh,然后提交<生产环境下,配置环节发生了变动>
问:如何刷新配置呢?
答:curl -X POST http:8081/refresh
["config.client.version","profile"] # 指的是profile属性发生了更新
- refresh scope是干什么用的?
问题:为什么要添加actuator这个依赖呢? 答:因为@RefreshScope这个是actuator拓展的"Endpoints"
- 分析请求刷新的方式的缺点
我们是通过refresh端点去刷新的,如果服务众多的情况下curl -X POST http:8081/refresh通过这个方式来刷新配置信息,会很容易发生问题!
但是refresh有点问题。。。。。暂时没搜索到解决办法!!
上述问题的解决办法<因为版本问题>
- 备注
NOTE | @RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behaviour: e.g. it does not mean that all the @Beans defined in that class are themselves @RefreshScope . Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope (in which it will be rebuilt on a refresh and its dependencies re-injected, at which point they will be re-initialized from the refreshed @Configuration ). |
如果说@RefreshScope和
@Configuration
放到同一个class类上时,从技术上来说是可以一起使用的,但是可能会造成不可思议的情况,所以。。。。。