企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
![](https://img.kancloud.cn/3a/98/3a98395d1e5c139c986ef08045fa6498_993x336.jpg) 当我修改存储在 Gitee 上的配置时,Config Server 不需要重启即可同步 Gitee 上的配置,但是 Config Client 需要重启才能进行同步。如果每次修改都要重启,那么将是一个噩梦。 <br/> 而下面将要学习的动态刷新就可以解决这个问题,当更改存储在 Gitee 上的配置时,客户端不再需要重启即可同步配置。 <br/> 步骤如下: **1. 在 cloud-config-client-3355 客户端的`pom.xml`中添加 `actuator` 依赖** ```xml <dependencies> <!-- config --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <!-- actuator --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> ... </dependencies> ``` **2. 在 cloud-config-client-3355 客户端的`bootstrap.yml`中暴露监控端口** ```yml #暴露监控端点 management: endpoints: web: exposure: include: "*" ``` **3. 在 cloud-config-client-3355 客户端的`ConfigController`上添加注解`@RefreshScope`** ```java @RestController @RefreshScope public class ConfigController { @Value("${app.version:default}") private String version; @Value("${app.name:default}") private String name; @GetMapping("/config") public String getConfigInfo() { return "app.name:" + name + ",version:" + version; } } ``` **4. 启动 3344 服务端和 3355 客户端** 在没有更新Gitee上的 `cloud-config-client-3355-test.yml` 配置文件前,访问 http://localhost:3355/config ,获取如下内容。 ``` app.name:cloud-config-client-3355,version:test-1.0 ``` **5. 到 Gitee 上修改 `cloud-config-client-3355-test.yml` 文件** 修改内容如下: ``` app: name: cloud-config-client-3355 version: test-2.0 #之前是 test-1.0 ``` 没有重启 cloud-config-client-3355 前提下,刷新 http://localhost:3355/config ,依旧是 `test-1.0`,说明 3355 客户端没有同步 Gitee 上的配置。 ``` app.name:cloud-config-client-3355,version:test-1.0 ``` **6. 运行下面的命令刷新 cloud-config-client-3355 客户端** ```shell curl -X POST http://localhost:3355/actuator/refresh ``` ![](https://img.kancloud.cn/e2/6b/e26b302478700f3afacf52a4ac6e168a_1218x184.jpg) 在没有重启 cloud-config-client-3355 客户端的前提下,刷新 http://localhost:3355/config ,可以看到由原来的 `test-1.0` 更新为 `test-2.0`,说明 3355 客户端已经与 Gitee 上的配置同步成功! ``` app.name:cloud-config-client-3355,version:test-2.0 ``` <br/> 但是上面讲的这种同步方式做不到这两点需求:广播通知和定点通知。 * 广播通知:即只需要通知其中某一个 config client 客户端,其它 config-client 也能知道配置更新了,这样就不用发送那么多次的`curl -X POST ...`请求。 * 定点通知:即我想更新哪个 config client 的配置我就更新哪一个的,不想更新的就不更新。 而且这种方式需要运维人员手动发送`curl -X POST ...`请求,本质上还是手动刷新,不是自动刷新,要解决这些问题,需要引入 Spring Cloud Bus 消息总线。