Spring cloud使用/refresh端点手动刷新配置

一 介绍
很多场景下,需要在运行期间动态调整配置。如果配置发生了修改,微服务也应该实现配置的刷新。
下面实现配置的手动刷新。
二 新建项目microservice-config-client-refresh
三 为项目添加spring-boot-starter-actuator依赖,该依赖包含了/refresh端点,用于配置的刷新。
  <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>
四 在Controller上添加注解@RefreshScope。添加@RefreshScope的类会在配置更改时得到特殊处理。
package com.itmuch.cloud.study.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class ConfigClientController {
  @Value("${profile}")
  private String profile;

  @GetMapping("/profile")
  public String hello() {
    return this.profile;
  }
}
五 测试
1 启动microservice-config-server
2 启动microservice-config-client-refresh
3 访问http://localhost:8081/profile,获得结果
dev-1.0
4 修改Git仓库中microservice-foo-dev.properties的文件内容为:
profile=dev-1.0-change
5 重新访问 http://localhost:8081/profile,获得结果依然是:
dev-1.0
6 发送post请求到 http://localhost:8081/refresh,结果返回
[
    "config.client.version",
    "profile"
]
7 再次访问 http://localhost:8081/profile,返回结果为:
dev-1.0-change
说明配置已经刷新

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/80872615
今日推荐