服务的注册与发现是微服务架构中的核心机制,而 Eureka(由 Netflix 开发,集成在 Spring Cloud 中)是这一机制的经典实现。以下是其关键概念和工作原理的清晰总结:
1. 为什么需要服务注册与发现?
- 动态性:微服务实例可能频繁变化(如扩缩容、故障迁移)。
- 解耦调用方与服务方:避免硬编码服务地址,提高灵活性。
- 负载均衡:支持动态选择可用实例,提升系统弹性。
2. 核心概念
Eureka Server(服务端)
- 作用:作为注册中心,管理所有微服务的注册信息。
- 高可用:支持多节点集群(节点间互相注册),如 eureka1 和 eureka2 相互同步数据。
Eureka Client(客户端)
- 服务提供者:向 Eureka Server 注册自身信息(如 IP、端口、健康状态)。
- 服务消费者:从 Eureka Server 获取服务列表,并调用其他服务。
3. 工作流程
服务注册
- 启动时注册:微服务(如 user-service)启动后,向 Eureka Server 发送注册请求。
- 元数据存储:Eureka Server 存储服务名、实例 ID、IP、端口等元数据。
服务续约(心跳)
- 客户端每 30 秒(默认)向 Eureka Server 发送心跳,证明自己存活。
- 若 Server 90 秒未收到心跳,则标记实例为不可用(但不会立即删除)。
服务发现
- 拉取服务列表:消费者(如 order-service)定期从 Eureka Server 获取服务列表。
- 负载均衡:通过 Ribbon 等组件,基于策略(轮询、随机等)选择实例发起调用。
服务下线
- 服务关闭时,主动发送下线请求到 Eureka Server,触发立即删除。
4. Eureka 的自我保护机制
- 触发条件:当短时间内丢失大量心跳(如网络分区故障)。
- 行为:Eureka Server 进入保护模式,保留现有服务实例(即使心跳失败),避免因瞬时故障误删实例。
- 配置:可通过 eureka.server.enable-self-preservation=false 关闭(生产环境慎用)。
5. 在 Spring Cloud 中集成 Eureka
步骤 1:搭建 Eureka Server
- 添加依赖:
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 启用注解:在主类添加 @EnableEurekaServer。
- 配置:
yaml
server:
port: 8761
eureka:
client:
register-with-eureka: false # 不自我注册
fetch-registry: false # 不拉取注册表
instance:
hostname: localhost
步骤 2:注册服务提供者
- 添加依赖:
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 配置:
yaml
spring:
application:
name: user-service # 服务名(用于发现)
eureka:
client:
service-url:
defaultZone:
http://localhost:8761/eureka # Eureka Server 地址
步骤 3:服务消费者调用
- 通过 DiscoveryClient 获取实例列表:
java
@Autowired
private DiscoveryClient discoveryClient;
List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
- 通过 Feign/Ribbon 负载均衡调用:
java
@FeignClient(name = "user-service")
public interface UserServiceClient {
@GetMapping("/users/{id}")
User getUser(@PathVariable Long id);
}
6. 高可用配置(Eureka 集群)
- 多节点配置:每个 Eureka Server 指向其他节点。
yaml
# eureka-server1 配置
eureka:
client:
service-url:
defaultZone: http://eureka-server2:8762/eureka
# eureka-server2 配置
eureka:
client:
service-url:
defaultZone: http://eureka-server1:8761/eureka
7. 常见问题与解决
- 服务未注册:检查配置的 defaultZone 和网络连通性。
- 服务列表未更新:调整客户端缓存时间或关闭自我保护。
- 负载均衡失效:确保服务名一致,且 Ribbon 配置正确。
通过 Eureka 的服务注册与发现,微服务架构实现了动态扩展和故障容错,是构建弹性分布式系统的基石。合理配置心跳、自我保护及集群策略,可显著提升系统稳定性。