一、注册中心
注册中心就是:存放服务器地址相关信息(接口地址)的一个服务端。
(注册中心是存放服务的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 禁用自我保护模式。