本節講解基於Eureka的服務發現。
Eureka簡介
Eureka是Netflix開源的服務發現組件,本身是一個基於REST的服務,包含Server和Client兩部分,Spring Cloud將它集成在子項目Spring Cloud Netflix中。
拓展閱讀
- Eureka的GitHub:<https://github.com/Netflix/Eureka>
- Netflix是一家在線影片租賃提供商。
- Eureka的典故:阿基米德發現浮力時,非常開心,於是說:“Eureka!”意思是“我找到了!”。Netflix將它們的服務發現組件命名爲Eureka實在是非常形象。
理解跟我學Spring Cloud(Finchley版)-04-服務註冊與服務發現-原理剖析 所講的服務發現原理後,我們來編寫基於Eureka的服務發現——首先編寫一個Eureka Server,然後將前文的微服務都註冊到Eureka Server上。
編寫Eureka Server
-
加依賴
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies>
-
加註解
@SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
-
寫配置
server: port: 8761 eureka: client: # 是否要註冊到其他Eureka Server實例 register-with-eureka: false # 是否要從其他Eureka Server實例獲取數據 fetch-registry: false service-url: defaultZone: http://localhost:8761/eureka/
TIPS
這裏,大家可先不去探究registerWithEureka
以及fetchRegistry
究竟是什麼鬼,筆者將在下一節爲大家揭曉。
將應用註冊到Eureka Server上
-
加依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
-
加註解
@SpringBootApplication public class ProviderUserApplication { public static void main(String[] args) { SpringApplication.run(ProviderUserApplication.class, args); } }
注意:早期的版本(Dalston及更早版本)還需在啓動類上添加註解
@EnableDiscoveryClient
或@EnableEurekaClient
,從Edgware開始,該註解可省略。 -
添加配置:
spring: application: # 指定註冊到eureka server上的服務名稱,對於電影微服務,本系列將名稱設爲microservice-consumer-movie name: microservice-provider-user eureka: client: service-url: # 指定eureka server通信地址,注意/eureka/小尾巴不能少 defaultZone: http://localhost:8761/eureka/ instance: # 是否註冊IP到eureka server,如不指定或設爲false,那就會註冊主機名到eureka server prefer-ip-address: true
測試
-
依次啓動Eureka Server以及用戶微服務、電影微服務;
-
訪問
http://localhost:8761
可觀察到類似如下界面: -
將用戶微服務停止,可看到Eureka Server首頁變成類似如下界面:
配套代碼
- GitHub:
- Eureka Server:<https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-discovery-eureka>
- microservice-provider-user:<https://www.github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-provider-user>
- microservice-consumer-movie:<https://github.com/eacdy/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie>
- Gitee:
- Eureka Server:<https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-discovery-eureka>
- microservice-provider-user:<https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-provider-user>
- microservice-consumer-movie:<https://gitee.com/itmuch/spring-cloud-study/tree/master/2018-Finchley/microservice-consumer-movie>
本文首發
<http://www.itmuch.com/spring-cloud/finchley-5/>