1. 程式人生 > >spring cloud註冊中心,服務提供作者,服務消費者的一些區別

spring cloud註冊中心,服務提供作者,服務消費者的一些區別

Spring Cloud Eureka, 使用Netflix Eureka來實現服務註冊與發現。

Eureka服務端,我們也稱為服務註冊中心。

  同其他服務註冊中心 一 樣,支援高可用配置。它依託於強 一 致性提供良好的服務例項可用性,可以應對多種不同的故障場景。如果Eureka以叢集模式部署,當叢集中有分片出現故障時,那麼Eureka就轉入自我保護模式。它允許在分片故障期間繼續提供服務的發現和註冊,當故障分片恢復執行時,叢集中的其他分片會把它們的狀態再次同步回來。以在AWS 上的實踐為例,Netflix推薦每個可用的區域執行 一 個Eureka服務端,通過它來形成叢集

Eureka客戶端,主要處理服務的註冊與發現。

客戶端服務通過註解和引數配置的方式,嵌入在客戶端應用程式的程式碼中,在應用程式執行時,Eureka客戶端向註冊中心註冊自身提供的服務並週期性地傳送心跳來更新它的服務租約。同時,它也能從服務端查詢當前注
冊的服務資訊並把它們快取到本地並週期性地重新整理服務狀態。

註冊中心搭建:

部分pom.xml

<dependencies>

     <dependency>
          <groupid>org.springframework.cloud</groupid>
          <artifactid>spring-cloud-starter-eureka-server</artifactid>
     </dependency>

</dependencies>

通過 @EnableEurekaServer 註解啟動 一 個服務註冊中心提供給其他應用進行對話。

在預設設定下, 該服務註冊中心也會將自己作為客戶端來嘗試註冊它自己,所以我們需要禁用它的客戶端註冊行為, 只需在 application.properties 中增加如下配置:

 eureka.client.register-with-eureka: 由於該應用為註冊中心,所以設定為 false, 代表不向註冊中心註冊自己。 

eureka.client.fetch-registry: 由於註冊中心的職責就是維護服務例項,它並不需要去檢索服務, 所以也設定為 false 

註冊服務提供者:

部分pom.xml:

<dependency>
     <groupid>org.springframework.boot</groupid>
     <artifactid>spring-boot-starter-web</artifactid>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupid>
     <artifactid>spring-boot-starter-test</artifactid>
<scope>test</scope>
</dependency>

<dependency>
     <groupid>org.springframework.cloud</groupid>
     <artifactid>spring-cloud-starter-eureka</artifactid>
</dependency>

 以下HelloController通過url  “xxx:xxx/hello”呼叫該方法 通過注入 DiscoveryClient物件, 在日誌中打印出服務的相關內容。

  在主類中通過加上 @EnableDiscoveryClient 註解,啟用Eureka中的DiscoveryClient 實現(自動化配置,建立 DiscoveryClient 介面針對 Eureka 客戶端的 EurekaDiscoveryClient 例項),才能實現上述 Controller 中對服務資訊的輸出。

配置檔案:

spring.application.name = hello-service

eureka.client.serviceUrl.defaultZone = http://localhost:llll/eureka/

服務消費的任務由Ribbon完成

它在Eureka服務發現的基礎上,實現了 一 套對服務例項的選擇策略,從而實現對服務的消費。

部分pom.xml

<dependencies>
     <dependency>
     <groupid>org.springframework.boot</groupid>
     <artifactid>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
     <groupid>org.springframework.cloud</groupid>
     <artifactid>spring-cloud-starter-eureka</artifactid>
</dependency>
<dependency>
     <groupid>org.springframework.cloud</groupid>
     <artifactid>spring-cloud-starter-ribbon</artifactid>
</dependency>

</dependencies>

  應用主類 ConsumerApplication, 通過 @EnableDiscoveryClient註解讓該應用註冊為 Eureka 客戶端應用, 以獲得服務發現的能力。 同時, 在該主類中建立 RestTemplate 的 Spring Bean 例項,並通過 @LoadBalanced 註解開啟客戶端負載均衡。

  建立ConsumerContioller類並實現/Ribbon-consumer介面 。通過在上面建立的RestTemplate 來實現對 H ELLO -SER VI CE服務提供的
/hello介面進行呼叫

 restTemplate:藉助 RestTemplate,Spring應用能夠方便地使用REST資源 Spring的 RestTemplate訪問使用了模版方法的設計模式.

getForEntity() 傳送一個HTTP GET請求,返回的ResponseEntity包含了響應體所對映成的物件。

配置檔案:

spring.applicatiion.name = ribbon-consumer
server.port=9000
eureka.client.serviceUrl.defaultZone = http://localhost:llll/eureka/