spring cloud學習(六) 配置中心-自動更新

上一篇學習了spring cloud config的基本使用,但發現有個問題,就是每次更改配置後,都須要重啓服務才能更新配置,這樣確定是不行的。在上網查資料瞭解後,spring cloud支持經過AMQP來實現配置的實時更新。html

1、安裝rabbitmq

1.1
若是要使用spring cloud的amqp,須要安裝rabbitmq。咱們能夠經過官網 https://www.rabbitmq.com/download.html 下載。我用的是mac,下載解壓後,執行$RABBITMQ_HOME/sbin/rabbitmq-server來啓動rabbitmq。git

rabbitmq的默認用戶和密碼都是guest,而默認端口是5672web

其餘rabbitmq相關的這裏就很少說了。spring

2、改造config-server和client-a

2.1
在config-server和client-a兩個模塊下的pom文件添加mvc

<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>

這裏說明下spring-boot-starter-actuator是spring-boot自帶的監控模塊,咱們要使用spring-cloud-starter-bus-amqp的話,也必須加上。app

2.2
修改client-a模塊的配置文件,主要是加上rabbitmq的配置,修改後以下,而config-server的配置文件不用修改spring-boot

server:
  port: 8910

eureka:
  client:
    serviceUrl:
          defaultZone: http://localhost:8010/eureka/

spring:
  application:
      name: client-a
  cloud:
      config:
        discovery:
          enabled: true #開啓經過服務來訪問Config Server的功能
          service-id: config-server
        profile: dev
        label: master

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

2.3
注意,要達到配置自動更新,這裏須要修改client-a的TestController,添加@RefreshScope註解post

@RestController
@RefreshScope
public class TestController {
    ...
}

2.4
重啓config-server和client-a學習

能夠注意下啓動日誌,其中應該有一段是
o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/bus/refresh],methods=[POST]}"
這就是觸發配置刷新的方式。日誌

打開http://localhost:8910/getProperties 應該看到配置仍是舊的配置

修改git上的配置文件

以post形式訪問配置中心的http://localhost:8030/bus/refresh 來觸發配置更新,看本地的日誌,config-server和client-a都會有刷新配置的日誌打印

再打開http://localhost:8910/getProperties 應該能夠看到配置已經更新了

2.5
如今雖然能夠不用重啓服務就更新配置了,但仍是須要咱們手動操做,這樣仍是不可取的。
因此,這裏就要用到git的webhooks來達到自動更新配置。

打開git上配置倉庫的地址,添加webhooks

上面的Payload URL就填寫咱們的配置中心觸發刷新的地址,固然這裏不能寫localhost啦,要外網訪問地址才行。

還有這裏面有個Secret的祕鑰驗證,若是這裏填寫的話,在配置文件上要寫上encrypt.key與之對應。

相關文章
相關標籤/搜索