服務治理 Spring Cloud Eureka
服務治理是微服務架構中最為核心和基礎的模塊,主要用來實作各個微服務實體的自動化注冊與發現,Spring Cloud Eureka 是 Spring Cloud Netflix 微服務套件中的一部分,基于 Netflix Eureka 做了二次封裝,主要負責完成微服務架構中的服務治理功能,
- 服務注冊
在服務治理框架中通常都會構建一個注冊中心,每個服務單元向注冊中心登記自己提供的服務,將埠,版本號,通信協議等附加資訊告知注冊中心,注冊中心按服務名分類組織服務清單,服務注冊中心還需要以心跳方式監測清單中的服務是否可用,不可用則從服務清單中剔除,達到排除故障服務的作用,
- 服務發現
在服務治理框架作用下,服務間的呼叫不再通過指定具體的實體的地址來實作,而是通過向服務名發起請求呼叫實作,所以,服務呼叫方在呼叫服務提供方介面的時候,并不知道服務實體具體的位置,服務呼叫方需要向服務注冊中心咨詢服務,獲取所有的服務實體清單,實作對具體服務實體的訪問,
1. 搭建服務注冊中心(Eureka 服務端)
1.1 服務注冊中心搭建
- 創建Spring Boot 工程
- 添加依賴: spring-cloud-starter-eureka-server
- 使用
@EnableEurekaServer開啟服務注冊中心
- 配置服務注冊中心
1.2 服務注冊中心配置
| name |
description |
value |
| spring.application.name |
服務名 |
- |
| server.port |
埠 |
- |
| eureka.instance.hostname |
主機名稱 |
- |
| eureka.client.register-with-eureka |
是否向注冊中心注冊自己 |
false |
| eureka.client.fetch-registry |
是否需要檢索服務 |
false |
| eureka.client.service-url.defaultZone |
服務注冊中心地址 |
http://\({eureka.instance.hostname}:\){server.port}/eureka/ |
2. 注冊服務提供者(Eureka 客戶端)
2.1 服務提供者注冊
- 創建Spring Boot 工程
- 添加依賴: spring-cloud-starter-eureka-client
- 使用
@EnableDiscoveryClient激活 discovery client
- 配置服務提供者
2.2 服務提供者配置
| name |
description |
value |
| spring.application.name |
服務名 |
- |
| server.port |
埠 |
- |
| eureka.client.service-url.defaultZone |
服務注冊中心地址 |
- |
3. 注冊服務消費者(Eureka 客戶端)
3.1 服務消費者注冊
- 創建Spring Boot 工程
- 添加依賴: spring-cloud-starter-eureka-client, spring-cloud-starter-ribbon
- 使用
@EnableDiscoveryClient激活 discovery client,在主類中創建RestTemplate的Spring Bean實體,并通過@LoadBalanced注解開啟客戶端負載均衡
- 配置服務提供者
3.2 服務消費者配置
| name |
description |
value |
| spring.application.name |
服務名 |
- |
| server.port |
埠 |
- |
| eureka.client.service-url.defaultZone |
服務注冊中心地址 |
- |
4. 高可用服務注冊中心
在分布式環境中,需要充分考慮發生故障的情況,所以在生產環境中必須對各個組件進行高可用部署,對于服務中心也一樣,在 Eureka 的服務治理設計中,所有節點既是服務提供方也是服務消費方,服務注冊中心也不例外,Eureka Server 高可用實際上就是將自己作為服務向其它服務注冊中心注冊自己,形成一組互相注冊的注冊中心,實作服務清單互相同步,達到高可用效果,
4.1 高可用服務注冊中心配置
| name |
description |
value |
| spring.application.name |
服務名 |
- |
| server.port |
埠 |
- |
| eureka.instance.hostname |
主機名稱 |
- |
| eureka.client.service-url.defaultZone |
服務注冊中心地址 |
其它服務注冊中心地址: url2,url3... |
4.2 服務提供方配置
| name |
description |
value |
| spring.application.name |
服務名 |
- |
| server.port |
埠 |
- |
| eureka.client.service-url.defaultZone |
服務注冊中心地址 |
其它服務注冊中心地址: url1,url2,url3... |
附. 常用配置
| name |
description |
default |
| spring.application.name |
服務名 |
- |
| server.port |
埠 |
- |
| eureka.instance.hostname |
主機名稱 |
- |
| eureka.instance.lease-renewal-interval-in-seconds |
服務續約任務的呼叫間隔時間 |
30 |
| eureka.instance.lease-expiration-duration-in-seconds |
服務失效時間 |
90 |
| eureka.client.register-with-eureka |
是否向注冊中心注冊自己 |
true |
| eureka.client.fetch-registry |
是否需要檢索服務 |
true |
| eureka.client.service-url.defaultZone |
eureka server 磁區地址 |
- |
| eureka.server.enable-self-preservation |
是否開啟保護機制 |
- |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/89862.html
標籤:Java
上一篇:我能想到的最浪漫的Java網路教程之Socket,三步到位!!!
下一篇:SpringCloud Ribbon (二)