上一篇文章讲了SpringCloudConfig
集成Git
仓库,配和 Eureka
注册中心一起使用,但是我们会发现,修改了Git
仓库的配置后,需要重启服务,才可以得到最新的配置,这一篇我们尝试使用 Refresh
实现主动获取 Config Server
配置服务中心的最新配置
把上一篇,示例代码下载,才可以进行一下的操作,下载地址在文章末尾
spring-cloud-eureka-service
spring-cloud-config-server
spring-cloud-eureka-provider-1
spring-cloud-eureka-provider-2
spring-cloud-eureka-provider-3
spring-cloud-feign-consumer
修改第九篇文章项目
spring-cloud-eureka-provider-1
spring-cloud-eureka-provider-2
spring-cloud-eureka-provider-3
<!-- actuator 监控 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
在 application.properties
添加以下配置.关闭安全认证
#关闭刷新安全认证
management.security.enabled=false
值是false
的话,除开health
接口还依赖endpoints.health.sensitive
的配置外,其他接口都不需要输入用户名和密码了
在程序的启动类 EurekaProviderApplication
通过 @RefreshScope
开启 SpringCloudConfig 客户端的 refresh
刷新范围,来获取服务端的最新配置,@RefreshScope
要加在声明@Controller
声明的类上,否则refres
h之后Conroller
拿不到最新的值,会默认调用缓存。
package io.ymq.example.eureka.provider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RefreshScope
@RestController
@EnableEurekaClient
@SpringBootApplication
public class EurekaProviderApplication {
@Value("${content}")
String content;
@Value("${server.port}")
String port;
@RequestMapping("/")
public String home() {
return "Hello world ,port:" + port+",content="+content;
}
public static void main(String[] args) {
SpringApplication.run(EurekaProviderApplication.class, args);
}
}
按照顺序依次启动项目
spring-cloud-eureka-service
spring-cloud-config-server
spring-cloud-eureka-provider-1
spring-cloud-eureka-provider-2
spring-cloud-eureka-provider-3
spring-cloud-feign-consumer
启动该工程后,访问服务注册中心,查看服务是否都已注册成功:http://localhost:8761/
http://127.0.0.1:9000/hello
Postman
发送 POST
请求到:http://localhost:8081/refresh,http://localhost:8083/refresh,访问服务,或者在浏览器访问http://127.0.0.1:9000/hello
F5 刷新
发现:服务8082 没有刷新到最新配置 因为没有手动触发更新
Spring Cloud(十)高可用的分布式配置中心 Spring Cloud Config 中使用 Refresh
原文:https://www.cnblogs.com/lukelook/p/11176255.html