天天看點

SpringCloud之Spring Cloud Bus消息總線

先了解一下

前提:首先必須安裝好RabbitMq。

    之前我們在Spring Cloud Config中提到,當更新了配置資訊之後,用戶端無法擷取到最新的配置資訊,那麼Spring Cloud Bus就可以用來解決這個問題。這裡我們借助RabbitMq來實作Server與Client端的消息通知。

    重新整理配置資訊大概流程:更新配置送出代碼之後,在Config-Server端發post請求/ actuator/bus-refresh,Server端收到請求會通知給Spring Cloud Bus,Bus接收到消息并通知給用戶端,用戶端收到消息後請求Server端擷取最新的配置,這樣用戶端最終就可以擷取到更新之後的配置資訊了。接下來我們修改完代碼之後,更新并送出代碼,請求Server端重新整理接口,重新通路用戶端,這時就可以擷取到最新的配置資訊了。

項目搭建

在springcloud-config-application的基礎上進行修改:

1、修改Config-Server端

在config-server端添加依賴:

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

application.yml添加配置:

spring:
  rabbitmq:
    host: *******
    port: 5672
    username: guest
    password: *******
management:
  endpoints:
    web:
      exposure:
        include: bus-refresh
           

config-server端重新整理接口:

http://localhost:8081/actuator/bus-refresh
           

2、修改Config-Client端

在config-client端添加依賴:

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

bootstrap.properties添加RibbitMq配置資訊

spring.rabbitmq.host=******
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=*****
spring.cloud.bus.enabled=true
spring.cloud.bus.trace.enabled=true
management.endpoints.web.exposure.include=bus-refresh
           

修改controller代碼:

添加注解:@RefreshScope

Config-Client端重新整理接口:

http://localhost:8083/actuator/bus-refresh
           

注:一般我們去重新整理Server端,重新通路所有的Client端,就會得到最新的配置資訊。

完整代碼如下:

https://gitee.com/superbutton/spring-cloud-study/tree/develop/springcloud-bus-application
           

繼續閱讀