服务注册与发现
→ 返回 Spring Cloud
服务注册与发现是微服务架构的基础设施,解决服务实例动态上下线时的地址管理问题,使调用方无需硬编码 IP,而是通过服务名发现可用实例。
核心流程
Provider 启动
│ 1. 注册(服务名 + IP + Port + 健康状态)
▼
注册中心(Registry)
│ 2. 订阅 / 通知(服务列表变更)
▼
Consumer
│ 3. 缓存本地地址列表
│ 4. 负载均衡选择实例
▼
Provider 实例
| 概念 | 说明 |
|---|
| 服务注册 | Provider 启动时向注册中心上报地址和元数据 |
| 心跳续约 | Provider 定期发送心跳,证明存活 |
| 服务发现 | Consumer 按服务名查询可用实例列表 |
| 服务下线 | Provider 关闭时注销,或心跳超时被剔除 |
两种发现模式
| 模式 | 说明 | 代表 |
|---|
| 客户端发现 | Consumer 自己查注册中心,自行负载均衡 | Eureka、Nacos |
| 服务端发现 | 请求打到 LB/网关,由其查注册中心转发 | AWS ELB、Kubernetes |
Spring Cloud 默认采用客户端发现模式。
主流注册中心对比
| 特性 | Nacos | Eureka | Consul | Zookeeper |
|---|
| CAP | AP/CP | AP | CP | CP |
| 配置中心 | ✅ | ❌ | KV | ❌ |
| 健康检查 | 心跳/主动 | 心跳 | 多种探针 | 临时节点 |
| 多数据中心 | 支持 | 弱 | 原生 | 不支持 |
| 维护状态 | 活跃 | 停维护 | 活跃 | 活跃 |
| Spring Cloud 推荐 | ⭐⭐⭐ | 遗留 | ⭐⭐ | ⭐ |
Spring Cloud + Nacos(推荐)
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
spring:
application:
name: order-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: dev
cluster-name: SH
ephemeral: true
@SpringBootApplication
@EnableDiscoveryClient
public class OrderServiceApp { ... }
Spring Cloud + Eureka(遗留)
# Server 端
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
# Client 端
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 30
DiscoveryClient API
@Autowired
private DiscoveryClient discoveryClient;
// 获取所有注册服务名
List<String> services = discoveryClient.getServices();
// 获取指定服务的所有实例
List<ServiceInstance> instances =
discoveryClient.getInstances("order-service");
instances.forEach(inst ->
System.out.println(inst.getHost() + ":" + inst.getPort()));
健康检查与优雅下线
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: health,info
# 触发优雅停机(Nacos 会自动摘除实例)
curl -X POST http://localhost:8080/actuator/shutdown
相关链接
Spring Cloud
架构与中间件
Redis / 数据库