Spring Cloud 如何动态刷新 Git 仓库配置?

文章结尾有彩蛋

有时候在配置中心有些参数是需要修改的,这时候如何不重启而达到实时生效的效果呢?

本文基于以下讲解:

  • Spring Cloud Greenwich.SR3

  • Spring Boot 2.1.7.RELEASE

  • 基于 Git 的配置中心仓库

添加 actuator 依赖

在引用配置中心的项目中添加以下 actuator 依赖:

<dependencies>
    ...
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>   
    ...
</dependencies>

spring-boot-starter-actuator:这个模块的 /actuator/refresh (POST请求)端点可以刷新配置,更多的使用参考 Spring Boot 系列文章。

暴露 refresh 端点

actuator 默认是不暴露 refresh 端点的,需要我们主动暴露,在引用配置中心的项目中添加以下配置:

management:
  endpoints:
    web:
      exposure:
        include: refresh,info,health

添加刷新范围

引用了配置中心的项目,在需要刷新的 Bean 上添加 @RefreshScope 注解。

示例1:

@RefreshScope
@RestController
public class TestController {

    @Value("${username}")
    private String username;

...

}

示例2:

@RefreshScope
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

...

}

当配置更改时,标有 @RefreshScope 的 Bean 将得到特殊处理来生效配置,不然改了配置不会刷新的。@RefreshScope 的原理可以参考这篇文章:Spring Cloud @RefreshScope 原理是什么?,很详细。

手动刷新配置

修改配置后,我们可以通过 post 到 /actuator/refresh 即可手动刷新配置。

如果参数有变更,刷新成功的话,会返回一个含有参数名的变更数组。

 

自动刷新配置

如果你使用了 Gitlab 或者 Github 仓库,可以配置 Webhooks 来做到自动更新,当参数变更时,能做到自动通知。

 

Github也差不多的,可以配置一个 URL(用于变更通知)和一个 Secret Token(用于请求验证)。

但这种方式仅限于单台,如果有多台或者多个系统,该如何通知,恐怕需要加一个公共接口来绕一圈了。

如果需要请求头认证的,可以使用这种方式:

https://user:password@ip:port/xxxx

 

spring cloud事务从入门到精通

(如下载连接失效,请私信我)

百度云下载链接:https://pan.baidu.com/s/1EtYyj7MEBqIGSYg2ljBFyg 提取码:n8p7

备份下载地址 https://huoyan-dabing.lanzous.com/b0d253o4h 密码:9sem
 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyb9292

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值