Spring Boot + Spring Cloud 构建微服务系统(十):配置中心(Spring Cloud Bus)

 

技术背景

我们在上一篇讲到,Spring Boot程序只在启动的时候加载配置文件信息,这样在GIT仓库配置修改之后,虽然配置中心服务器能够读取最新的提交信息,但是配置中心客户端却不会重新读取,以至于不能及时的读取更新后的配置信息。这个时候就需要一种通知刷新机制来支持了。

Refresh机制

refresh机制是Spring Cloud Config提供的一种刷新机制,它允许客户端通过POST方法触发各自的/refresh,只要依赖spring-boot-starter-actuator包就拥有了/refresh的功能,下面我们为我们的客户端加上刷新功能,以支持更新配置的读取。

添加依赖

修改 spring-cloud-conifg-client,添加监控依赖,监控依赖包里携带了 /refresh 的功能。

复制代码
<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-actuator</artifactId></dependency>
复制代码

开启更新机制

在使用配置属性的类型加上 @RefreshScope 注解,这样在客户端执行 /refresh 的时候就会刷新此类下面的配置属性了。

复制代码
package com.louis.spring.cloud.config.client.controller;  import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;  @RefreshScope @RestController class HelloController {          @Value("${spring.config.hello}")     private String hello;      @RequestMapping("/hello")     public String from() {         return this.hello;     } }
复制代码

修改配置

修改配置文件添加以下内容,开放refresh的相关接口。

bootstrap.yml

复制代码
management:   endpoints:     web:       exposure:         include: "*"
复制代码

这样,以后以post请求的方式访问 http://localhost:8552/actuator/refresh 时,就会更新修改后的配置文件了。

特别注意:

这里存在着版本大坑,1.x跟2.x的配置不太一样,我们用的是2.0+版本,务必注意。

1.安全配置变更

新版本

management.endpoints.web.exposure.include="*"

老版本

management.security.enabled=false

2.访问地址变更

新版本

http://localhost:8552/actuator/refresh

老版本

http://localhost:8552/refresh

这里还是解释一下上面这个配置起到了什么具体作用,其实actuator是一个健康检查包,它提供了一些健康检查数据接

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信