Spring Cloud Bus實現自動更新配置


一、概述

1. 配置環境

  版本:Spring Boot版本2.0.3.RELEASE,Spring Cloud版本Finchley.SR1,RabbitMQ 3.7.7

  說明:本文章是在https://www.cnblogs.com/wslook/p/9994251.html的基礎上完成,

2. 實現原理(如下圖所示)

  1. 通過消息隊列MQ傳遞消息
  2. 修改配置,對外暴露/actuator/bus-refresh接口
  3. 手動訪問/actuator/bus-refresh刷新配置;或者在git服務器(碼雲、GitHub等)上配置WebHooks,實現自動調用/actuator/bus-refresh接口,從而刷新配置(推薦)

二、Config Server端配置

1. 添加依賴

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

2. 修改配置

spring:
  # Rabbitmq配置
  rabbitmq:
    cache:
      channel:
        checkout-timeout: 1s
    host: 192.168.2.246
    port: 5672
    username: admin
    password: admin

#暴露/actuator/bus-refresh接口
management:
  endpoints:
    web:
      exposure:
        include: "*"

3. 啟動Config-Server,查看MQ,會多出來一個隊列

三、Config Client端配置

1. 添加依賴

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

2. 添加RabbitMQ配置

spring:
  # Rabbitmq配置
  rabbitmq:
    cache:
      channel:
        checkout-timeout: 1s
    host: 192.168.2.246
    port: 5672
    username: admin
    password: admin

3. 在使用屬性的地方,增加@RefreshScope注解,防止刷新后配置不生效----------但測試發現,不添加@RefreshScope注解也能動態刷新配置

//@RefreshScope
@Configuration
@ConfigurationProperties("aliyun")
public class OSSProperties {

    /**
     * 內網連接地址
     */
    private String endpoint;

    /**
     * 外網連接地址
     */
    private String outsideEndpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;

    /**
     * 外網訪問地址
     */
    private String url;

    private String roleArnPro;

    ...get set...          

}

四、測試(這里使用手動刷新的方式)

1. 啟動Client端服務,使用postman請求測試接口

2. 修改git服務器上的配置

3. 調用Config Server的/actuator/bus-refresh接口

Config Server控制台日志:

Config Client控制台日志:

RabbitMQ管理頁面:

4. 重新請求測試接口,發現在沒重啟的情況下,配置已經改變

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM