Eureka是Netflix开发的服务发现框架,SpringCloud将它集成在自己的子项目
spring-cloud-netflix
中,实现SpringCloud的服务发现功能。
简介
Eureka包含两个组件:Eureka Server
和Eureka Client
Eureka Server
提供服务注册服务,各个节点启动后,会在Eureka Server中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息
Eureka Client
是一个java客户端,用于简化与Eureka Server的交互
- 客户端同时也就别一个内置的、使用轮询(round-robin)负载算法的负载均衡器。
- 在应用启动后,将会向Eureka Server发送心跳,默认周期为30秒
如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除(默认90秒)
Eureka服务端开发
父工程pom.xml定义SpringCloud版本 <!--锁版本--> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.M9</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> eureka模块pom.xml引入eureka-server依赖 <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies> 添加application.yml server: port: 6868 eureka: client: fetch-registry: false #是否将自己注册到Eureka服务中,本身就是所以无需注册 register-with-eureka: false #是否从Eureka中获取注册信息 service-url: #Eureka客户端与Eureka服务端进行交互的地址 defaultZone: http://127.0.0.1:6868/eureka/ 编写启动类 @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } } 启动运行启动类,然后在浏览器地址栏输入 http://localhost:6868/
服务注册
依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> 每个微服务的application.yml,添加注册eureka服务的配置 eureka: client: service-url: defaultZone: http://127.0.0.1:6868/eureka/ instance: ip-address: true 启动类添加注解 @EnableEurekaClient
保护模式
Eureka Server
在运行期间,会统计心跳失败的比例在15分钟之内是否低于85%,
如果出现低于的情况(在单机调试的时候很容易满足,实际在生产环境上通常是由于网络不稳定导致),Eureka Server
会将当前的实例注册信息保护起来,同时提示警告。
保护模式主要用于一组客户端
和Eureka Server
之间存在网络分区场景下的保护。
一旦进入保护模式,Eureka Server将会尝试保护其服务注册表中的信息,不再删除服务注册表中的数据(也就是不会注销任何微服务)