Spring Cloud Bus實現自動更新配置

1、概述

1. 配置環境html

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

  說明:本文章是在http://www.javashuo.com/article/p-cwttcamw-cs.html的基礎上完成,web

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

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

2、Config Server端配置

1. 添加依賴服務器

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

2. 修改配置ide

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,會多出來一個隊列post

3、Config Client端配置

1. 添加依賴測試

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

2. 添加RabbitMQ配置url

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

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

//@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...          

}

4、測試(這裏使用手動刷新的方式)

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

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

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

Config Server控制檯日誌:

Config Client控制檯日誌:

RabbitMQ管理頁面:

4. 從新請求測試接口,發如今沒重啓的狀況下,配置已經改變

相關文章
相關標籤/搜索