在上一弹:Spring Cloud教程 第十一弹 Spring Cloud Config连接git和数据库 中介绍了spring cloud config的基本使用,但是配置无法动态刷新,也就是说如果我更改了git或数据库中的配置,项目必须重新启动才能使新配置生效。
注意:
下面介绍两种不重启项目便可以刷新配置的方式:
步骤如下。
org.springframework.boot spring-boot-starter-actuator
management:endpoints:web:exposure:include: "*"
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 DynamicRefreshController {@Value("${stuName:\"\"}")private String stuName;@GetMapping("/config")public void init(){System.out.println("stuName="+stuName);}
}
Spring Cloud Bus 实现配置的动态刷新步骤:
Spring Cloud Bus需要引入RabbitMQ或Kafka作为消息传输的媒介。
与手动刷新不同,动态刷新的改造主要在config server项目中。
步骤如下:
org.springframework.cloud spring-cloud-starter-bus-amqp
org.springframework.boot spring-boot-starter-actuator
management:endpoints:web:exposure:include: "*"
spring:rabbitmq:host: localhostport: 5672username: guestpassword: guest
5.config client引入依赖:
org.springframework.cloud spring-cloud-starter-bus-amqp
spring:rabbitmq:host: localhostport: 5672username: guestpassword: guest
bus-refresh端点原理: