Spring Cloud–Eureka(一)
在微服务架构中,服务的粒度小,数量会成倍的增加,有效管理服务的注册信息尤为重要。我们对注册中心的期望主要有:
- 简单易用:最好对开发者透明
- 高可用:几台注册中心坏掉不会导致整个服务瘫痪,注册服务整体持续可用
- 避免跨越机房调用:最好调用优先同一个机房的服务以减少网络延迟
- 跨语言:允许开发者使用多种编程语言构建微服务
构建一个注册中心
- 引入依赖 (注意版本)
1.
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
2.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
3.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
4.
编写main方法加注解
@SpringBootApplication
@EnableEurekaServer
public class AlanRegistryServer {
public static void main(String[] args) {
SpringApplication.run(AlanRegistryServer.class, args);
}
} 客户端
1. `<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>` 2. `<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.RC1</version> <type>pom</type> <scope>import</scope> </dependencies> </dependencyManagement>` 3. `加注解 @SpringBootApplication @EnableEurekaClien public class RegistryClientApplication { public static void main(String[] args) { SpringApplication.run(RegistryClientApplication.class, args); } }`
需要给微服务应用取个名字
注册中心:spring.application.name=eureka-server
服务:spring.application.name=bugfix-center
高可用
Eureka通过“伙伴”机制实现高可用。每一台Eureka都需要在配置中指定另一个Eureka的地址作为伙伴,Eureka启动时会向自己的伙伴节点获取当前已经存在的注册列表, 这样在向Eureka集群中新加机器时就不需要担心注册列表不完整的问题。
除此之外,Eureka还支持Region和Zone的概念。其中一个Region可以包含多个Zone。Eureka在启动时需要指定一个Zone名,即当前Eureka属于哪个zone, 如果不指定则属于defaultZone。Eureka Client也需要指定Zone, Client(当与Ribbon配置使用时)在向Server获取注册列表时会优先向自己Zone的Eureka发请求,如果自己Zone中的Eureka全挂了才会尝试向其它Zone。Region和Zone可以对应于现实中的大区和机房,如在华北地区有10个机房,在华南地区有20个机房,那么分别为Eureka指定合理的Region和Zone能有效避免跨机房调用,同时一个地区的Eureka坏掉不会导致整个该地区的服务都不可用。
Spring Cloud Netflix对微服务的支持还有:
- Hystrix: 断路器和资源隔离
- Feign: 声明式HTTP REST请求客户端
- Ribbon: 与Eureka结合实现软负载均衡
- Zuul: API请求路由,即Api Gateway
- Bus: 各个微服务节点之间的消息通讯
- Config: 配置的中央化存储
剔除过期等不健康实例(生产环境不建议使用)
server端:
1.关闭注册中心自我保护机制
eureka.server.enable-self-preservation:false
2.注册中心清理间隔(单位毫秒,默认60*1000)
eureka.server.eviction-interval-timer-in-ms:10000
client端:
1.开启健康检查(需要spring-boot-starter-actuator依赖)
eureka.client.healthcheck.enabled:true
2.租期更新时间间隔(默认30秒)
eureka.instance.lease-renewal-interval-in-seconds=10
3.租期到期时间(默认90秒)
eureka.instance.lease-expiration-duration-in-seconds=15
以上参数配置下来,从服务停止,到注册中心清除不健康实例,时间大约在30秒左右。租期到期时间为30秒时,清除时间大约在59秒,若采用默认的30-60配置,清除时间大约在2分半(以上均在关闭保护机制情况下),生产环境建议采用默认配置,服务停止到注册中心清除实例之间有一些计算什么的。