SpringCloud bus 手动post可用 使用webhooks自动更新配置失效的解决小记

先说解决办法:

查阅网上资料发现大家的问题其实都出在少了一个依赖,而不应该手动去拦截。这个依赖加在配置中心上

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-monitor</artifactId>
        </dependency>

 


在GitHub上创建了一个仓库用来存储配置。

配置中心及消费端要使用消息总线都要添加的依赖:

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

配置中心的配置文件application.yml:

spring:
  application:
    name: config
  cloud:
    config:
      server:
        git:
          uri: https://github.com/37176427/config-repo.git
          username: 
          password: 
          #配置存储目录
          basedir: /fileRoot/config/baseDir
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
management:
  endpoints:
    web:
      exposure:
        include: "*"

client端的配置文件bootstrap.yml:

spring:
  application:
    name: order
  cloud:
    config:
      discovery:
        enabled: true
        service-id: CONFIG
      profile: dev

测试使用的controller,直接输出env变量来观察是否更新了该配置:

@RestController
@RequestMapping("/env")
@RefreshScope
public class EnvController {

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

    @GetMapping("/print")
    public String print() {
        return env;
    }
}

项目运行并访问localhost:8081/env/print路径后,成功输出配置文件中的值。

当访问配置中心http://localhost:8080/order-dev.yml时 会输出最新的值 因为他去GitHub上拉取文件了

在GitHub上更改了值后,再次访问消费端路径 localhost:8081/env/print,并没有更新为新值,没有同步到最新的配置

发起一个post请求  curl -v -X POST "http://localhost:8080/actuator/bus-refresh" 此时的路径是/actuator/bus-refresh

可以看到配置中心config项目有新打印的日志 访问消费端/env/print后 值更新为最新值。

为了避免每次都要手动发起post请求来更新配置的弊端 使用了GitHub中的webhooks,它可以在每次该仓库有push时,对你设定的url发起一个post请求。

这里设定的路径为 http://外网域名/monitor    这个外网域名可以用natapp免费申请。正常情况下webhooks发起的post请求不应该返回400 404等错误

大多问题出现在这里,网上很多解决方案其实就是将这个post请求进行拦截,然后去调用/actuator/bus-refresh这个之前手动更新配置的路径来规避错误。

加上上述这个依赖后,重启项目,对/monitor路径进行post请求就不会出错了。

再次试验对配置进行更新后,访问消费端,成功读取到了最新的配置值。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值