zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

spring cloud config 结合 spring cloud bus实现配置自定的刷新

2023-02-18 16:27:59 时间

    在线上环境中,有时候我们希望系统中的某些配置参数在修改后,可以立即生效而不用重新启动服务。由上一节我们知道,我们可以把配置文件统一放到配置服务中进行管理,这一节我们在配置中心中整合spring cloud bus并结合gitwebhook实现配置的自动刷新。

    整合spring cloud bus后我们可以获取到一些新的端点:

    POST  /bus/refresh: 用于刷新配置

    POST  /bus/refresh?destination=spring.application.name:port 刷新具体的某个微服务,port和前面的name可以使用通配符 *

需求

    实现系统中的配置的自动刷新

实现步骤(在上一节代码的基础上)

     1、安装 erlang 和 rabbitmq, 需要注意 rabbitmq不同的版本需要不同的erlang的版本,参考链接 https://www.rabbitmq.com/which-erlang.html

     2、config server 和 config client 端同时引入以下依赖

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

    3、需要动态刷新配置的地方加上 @RefreshScope 注解

         此处是从配置中心获取  msg 这个字段的值,记住这个controller 的访问路径,下方演示需要用到

@RestController
@RefreshScope
public class PrintMsgController {
	@Value("${msg}")
	private String msg;
	/**
	 * 打印msg消息
	 *
	 * @return
	 */
	@GetMapping("print/msg")
	public String print() {
		return msg;
	}
}

    4、找到 git 的远程仓库,配置 webhook,这里以 github为例

    5、配置中心和配置客户端的代码 配置文件和上节差不多,唯一不同的是加入rabittmq 的配置

spring: 
  rabbitmq: 
    host: localhost
    port: 5672
    username: guest
    password: guest

 

运行结果


 

    解释:

         1、演示 config server 的代码

         2、演示 config client 的代码

         3、服务注册中心上各个服务注册的情况

         4、演示 webhook的配置(webhook配置的地址需要是外网可以访问的,我上方的例子是使用了一个内网穿透工具)

         5、更新 git 仓库上的配置,看各个客户端是否都更新

         6、取消webhook,然后开效果

         7、在 chrome 浏览器中演示如何只更新某个具体的微服务或使用通配符更新

 

完整代码

配置动态刷新完整代码:https://gitee.com/huan1993/spring-cloud-parent/tree/master/config/config-bus-webhook