一、註冊中心
註冊中心就是:存放服務器地址相關信息(接口地址)的一個服務端。
(註冊中心是存放服務的ip地址的,通常叫serviceId ,它以key-value(serviceName-172.0.0.1:8080)形式保存服務實際地址。)
1.SpringCloud支持哪些註冊中心
Eureka、Consul(go語言編寫)、Zookeeper
2.Dubbo支持常用註冊中心
Zookeeper、Redis
3.服務註冊發現原理
(1)服務註冊
將服務註冊到註冊中心上
(2)服務發現
從註冊中心上獲取服務信息
(3)服務提供者
提供服務接口
(4)服務消費者
調用別人接口
服務註冊與發現如下圖:
二、搭建eureka註冊中心
注意:這裏都是基於前面“微服務項目準備”進一步完善微服務項目,“微服務項目準備”鏈接地址:
https://blog.csdn.net/tengqingshan110/article/details/101282164
1.創建maven-module
在microservice父項目中創建microservice-eureka2001:
2.添加相關依賴
pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.syr.springcloud</groupId>
<artifactId>microservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>microservice-eureka2001</artifactId>
<dependencies>
<!--eureka-server服務端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-eureka-server</artifactId>
</dependency>
<!-- 修改後立即生效,熱部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
3.配置eurekaService
application.yml:
server:
port: 2001
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #不註冊
fetch-registry: false #不發現
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
4.啓動類上開啓eureka
package com.syr.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5.測試
出現上圖表示eureka註冊中心啓動成功,紅色部分爲eureka自我保護機制
6.自我保護
默認情況下,如果EurekaServer在一定時間內沒有接收到某個微服務實例的心跳,EurekaServer將會註銷該實例(默認90秒)。但是當網絡分區故障發生時,微服務與EurekaServer之間無法正常通信,以上行爲可能變得非常危險了——因爲微服務本身其實是健康的,此時本不應該註銷這個微服務。Eureka通過“自我保護模式”來解決這個問題——當EurekaServer節點在短時間內丟失過多客戶端時(可能發生了網絡分區故障),那麼這個節點就會進入自我保護模式。一旦進入該模式,EurekaServer就會保護服務註冊表中的信息,不再刪除服務註冊表中的數據(也就是不會註銷任何微服務)。當網絡故障恢復後,該Eureka Server節點會自動退出自我保護模式。
在自我保護模式中,Eureka Server會保護服務註冊表中的信息,不再註銷任何服務實例。當它收到的心跳數重新恢復到閾值以上時,該Eureka Server節點就會自動退出自我保護模式。它的設計哲學就是寧可保留錯誤的服務註冊信息,也不盲目註銷任何可能健康的服務實例。
綜上,自我保護模式是一種應對網絡異常的安全保護措施。它的架構哲學是寧可同時保留所有微服務(健康的微服務和不健康的微服務都會保留),也不盲目註銷任何健康的微服務。使用自我保護模式,可以讓Eureka集羣更加的健壯、穩定。
在Spring Cloud中,可以使用eureka.server.enable-self-preservation = false 禁用自我保護模式。