spring cloud微服務分散式雲架構-Spring Cloud Bus

springcloud885發表於2019-03-14

spring CloudBus 將分散式的節點和輕量的訊息代理連線起來。這可以用於廣播配置檔案的更改或者其他的管理工作。一個關鍵的思想就是,訊息匯流排可以為微服務做監控,也可以作為應用程式之間相互通訊。Spring Cloud大型企業分散式微服務雲架構原始碼請加一七九一七四三三八零

一、準備工作

本文還是基於上一篇文章來實現。按照官方文件,我們只需要在配置檔案中配置 spring-cloud-starter-bus-amqp ;這就是說我們需要裝rabbitMq,點選rabbitmq下載。至於怎麼使用 rabbitmq,搜尋引擎下。

二、改造config-client

在pom檔案加入spring-cloud-starter-bus-amqp,完整的配置檔案如下:

<dependencies>       
 <dependency>         
   <groupId>org.springframework.cloud</groupId>      
      <artifactId>spring-cloud-starter-config</artifactId>   
     </dependency>    
     <dependency>          
  <groupId>org.springframework.boot</groupId>   
         <artifactId>spring-boot-starter-web</artifactId>      
  </dependency> 
        <dependency>      
      <groupId>org.springframework.cloud</groupId>     
       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>    
    </dependency>        
 <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.properties中加上RabbitMq的配置,包括RabbitMq的地址、埠,使用者名稱、密碼。並需要加上spring.cloud.bus的三個配置,具體如下:

spring.rabbitmq.host=localhostspring.rabbitmq.port=5672spring.rabbitmq.username=guestspring.rabbitmq.password=guest
spring.cloud.bus.enabled=truespring.cloud.bus.trace.enabled=truemanagement.endpoints.web.exposure.include=bus-refresh
複製程式碼

ConfigClientApplication啟動類程式碼如下:

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@RestController
@RefreshScopepublic class ConfigClientApplication {   
  /**     * http://localhost:8881/actuator/bus-refresh     */    
 public static void main(String[] args) {      
  SpringApplication.run(ConfigClientApplication.class, args);   
 } 
    @Value("${foo}")    
String foo;  
   @RequestMapping(value = "/hi")   
 public String hi(){     
   return foo;  
  }}
複製程式碼

依次啟動eureka-server、confg-cserver,啟動兩個config-client,埠為:8881、8882。

訪問http://localhost:8881/hi 或者http://localhost:8882/hi 瀏覽器顯示:foo version 3

這時我們去程式碼倉庫將foo的值改為“foo version 4”,即改變配置檔案foo的值。如果是傳統的做法,需要重啟服務,才能達到配置檔案的更新。此時,我們只需要傳送post請求:http://localhost:8881/actuator/bus-refresh,你會發現config-client會重新讀取配置檔案

這時我們再訪問http://localhost:8881/hi 或者http://localhost:8882/hi 瀏覽器顯示:foo version 4

另外,/bus/refresh介面可以指定服務,即使用”destination”引數,比如 “/bus/refresh?destination=customers:**” 即重新整理服務名為customers的所有服務,不管ip。

相關文章