服務註冊中心
在服務治理框架中,通常有一個 服務註冊中心
,提供:
- 服務註冊。
每個服務單元向其登記自己提供的服務,將主機、端口號、版本號等告知註冊中心,註冊中心按
服務名
來組織清單。 - 服務發現。 服務調用方需要調用某個服務名的實例提供的服務,則向服務註冊中心獲取所有服務實例的清單,以實現對具體服務實例的訪問。
# first build.gradle
dependencies {
compile 'org.springframework.cloud:spring-cloud-starter-eureka-server'
compile 'org.springframework.boot:spring-boot-starter-web'
……
}
# second application.yaml
server:
port: 11111
eureka:
instance:
hostname: localhost
lease-renewal-interval-in-seconds: 30
lease-expiration-duration-in-seconds: 90
server:
enable-self-preservation: false
client:
fetch-registry: false
register-with-eureka: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
# third Application.java
@EnableEureKaServer
Netflix Eureka由於使用Restful API協議,因此支持跨語言跨平臺的微服務應用進行註冊。
服務提供者
Eureka客戶端:
- 向註冊中心登記自身提供的服務,並且週期性地發送心跳來更新它的服務租約。
- 從註冊中心查詢服務清單,把它們緩存到本地,並週期性地刷新服務狀態。
服務續約(renew)
在服務註冊完成之後,服務提供者維護一個心跳用來持續告知服務中心,以防止被服務列表中剔除。 使用spring boot actuator提供的/health來維護心跳、提供健康檢查。
#first build.gradle
dependencies {
compile 'org.springframework.cloud:spring-cloud-starter-eureka'
compile 'org.springframework.boot:spring-boot-starter-actuator'
……
}
#second application.yaml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:11111/eureka
#third Application.java
@EnableDiscoveryClient
服務下線
服務提供者正常關閉時,會觸發一個服務下線的Restful請求給註冊中心。註冊中心在收到請求後,會將該服務編輯爲下線,並廣播此事件。
服務剔除
註冊中心會定時每個一段時間 lease-renewal-interval-in-seconds ,將服務清單中超過時間 lease-expiration-duration-in-seconds 秒沒有續約的服務剔除出去。
自我保護
基於上面服務剔除的,註冊中心在運行期間,會統計心跳失敗的比例在15分鐘內是否低於85%,如果是,註冊中心會將當前註冊信息保護起來,讓其不會過期。
由於本地很容易觸發保護機制,因此本地開發時關閉自我保護。
# application.yaml
server:
enable-self-preservation: false