14.6.1 手动刷新配置属性

在第 16 章中,我们将介绍 Spring Boot Actuator,它是一个 Spring Boot 基础组件,它支持观察和有限操作应用程序 的运行时信息,例如修改日志记录级别。但现在,我们将看一个具体的 Actuator 特征,仅在配置为 Spring Cloud Config Server 客户端时才启用。

每当您配置一个应用程序使用 Config Server 的配置服务,自动配置还可以配置一个 Actuator 接口以用于刷新配置。要使用此接口,您需要添加 Actuator 依赖项:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

您可能已经猜到的,这个依赖项也可以从 Spring Initializr 中获得,通过勾选 Actuator 复选框。

有了 Actuator,您就可以任何时候对 /actuator/refresh 接口发送 HTTP POST 请求,强制从后端存储中获取最新配置。

要看到是如何实际操作的,先假设您有一个类 GreetingProps,并添加了 @ConfigurationProperties 注解:

@ConfigurationProperties(prefix="greeting")
@Component
public class GreetingProps {
  private String message;
  public String getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}

此外,您还有一个 Controller 类,它注入了 GreetingProps,对 GET 请求简单返回消息属性的值:

@RestController
public class GreetingController {
  rivate final GreetingProps props;
  public GreetingController(GreetingProps props) {
    this.props = props;
  }
  @GetMapping("/hello")
  public String message() {
    return props.getMessage();
  }
}

同时,在 Git 配置存储库中,有一个 application.yml 文件,其中有以下属性:

greeting:
  message: Hello World!

有了 Config Server 和这个简单的配置客户端,对接口 /hello 的 HTTP GET 请求将产生以下响应:

$ curl localhost:8080/hello
Hello World!

现在,在不重启 Config Server 和应用程序的情况下,更改 application.yml 文件中的 greeting.message 属性值,并将其推入后端 Git 存储库:

greeting:
  message: Hiya folks!

如果您对应用程序发出同样的 GET 请求,您仍然会得到同样的“Hello World!” 响应,即使 Git 中的配置已更改。但是,您可以通过发送 POST 请求来强制刷新:

$ curl localhost:53419/actuator/refresh -X POST
["config.client.version","greeting.message"]

请注意,响应是一个 JSON 数组包,其中含了已经更改的属性的名称 。该数组中包含 greeting.message 属性。还包括 config.client.version 属性,这个属性保存的是 Git 提交的哈希值。因为现在的配置是基于一个新的 Git 提交,每当文件中有任何更改时,这个属性都会更改。

POST 请求的响应告诉您 greeting.message 已更改。再次向 /hello 路径发出 GET 请求来验证一下:

$ curl localhost:8080/hello
Hiya folks!

不需要重新启动应用程序,也不需要重新启动 Config Server,应用程序为 greeting.message 属性使用了新值!

如果希望完全控制更新时机,调用 /actuator/refresh 接口非常合适。但如果应用程序是由多个微服务(可能每个服务还有多个实例),用这种方式将配置传播到所有应用就很繁琐。我们来看看怎么做到修改配置后,自动全部更新到所有应用中。

results matching ""

    No results matching ""