Spring Cloud 集成 Eureka 实战
前面几篇讲原理,这篇把整个链路跑起来:注册中心 + 两个服务提供者 + 一个消费者,包含服务调用、负载均衡、健康检查。代码基于 Spring Boot 3.2 + Spring Cloud 2023.x,用当前主流版本,不碰已经被移除的老 API(Ribbon 已于 2020 年后进入维护,这里用 Spring Cloud LoadBalancer)。
整体结构
eureka-server 注册中心,端口 8761
user-service 服务提供者,端口 8081(起两个实例:8081、8082)
order-service 服务消费者 + 提供者,端口 8083,调用 user-serviceorder-service 既调 user-service,也注册到 Eureka——真实项目里这种双重身份最普遍。
一、注册中心
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>Spring Cloud 版本用 BOM 管:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2023.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>启动类
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}配置
server:
port: 8761
spring:
application:
name: eureka-server
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false二、服务提供者:user-service
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>启动类
@SpringBootApplication
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}从 Spring Cloud Edgware 开始,@EnableDiscoveryClient 不再是必须的——classpath 上有 Eureka Client 且配了 service-url,自动配置就会注册。写不写都行,写了更直观。
业务代码
@RestController
@RequestMapping("/users")
public class UserController {
@Value("${server.port}")
private String port;
@GetMapping("/{id}")
public Map<String, Object> getById(@PathVariable Long id) {
// 返回端口号,方便验证负载均衡打到了哪个实例
return Map.of(
"id", id,
"name", "user-" + id,
"from", "user-service:" + port
);
}
}配置
server:
port: 8081
spring:
application:
name: user-service
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10 # 演示环境调快,方便观察
client:
service-url:
defaultZone: http://localhost:8761/eureka
healthcheck:
enabled: true # 健康检查驱动 UP/DOWN第二个实例用命令行覆盖端口启动:
java -jar user-service.jar --server.port=8082两个实例注册后,Dashboard 里 USER-SERVICE 下有两行,instanceId 分别是 192.168.x.x:user-service:8081 和 ...:8082。
三、消费者:order-service
依赖
在 user-service 的基础上,加 OpenFeign(声明式调用,比拼 RestTemplate 字符串可读性好):
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>启动类
@SpringBootApplication
@EnableFeignClients // 开启声明式客户端
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}Feign 客户端
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/users/{id}")
Map<String, Object> getById(@PathVariable("id") Long id);
}name = "user-service" 就是注册中心里的服务名。Feign 底层集成 Spring Cloud LoadBalancer,自动按服务名选实例。
控制器
@RestController
@RequestMapping("/orders")
public class OrderController {
private final UserClient userClient;
public OrderController(UserClient userClient) {
this.userClient = userClient;
}
@GetMapping("/{id}")
public Map<String, Object> getById(@PathVariable Long id) {
Map<String, Object> user = userClient.getById(id);
return Map.of(
"orderId", id,
"user", user,
"remark", "订单服务调用用户服务成功"
);
}
}配置
server:
port: 8083
spring:
application:
name: order-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
# Feign 超时与重试,生产必配
spring:
cloud:
openfeign:
client:
config:
default:
connect-timeout: 2000
read-timeout: 5000connect-timeout 2 秒是关键——注册表里有死实例时,快速失败换下一个,别傻等默认的 10 秒。
四、跑起来验证
启动顺序:eureka-server → user-service × 2 → order-service。
# 连续调用,观察 from 字段在 8081 和 8082 之间轮询
curl http://localhost:8083/orders/1001返回示例:
{
"orderId": 1001,
"user": {
"id": 1001,
"name": "user-1001",
"from": "user-service:8081"
},
"remark": "订单服务调用用户服务成功"
}多调几次,from 在 8081/8082 之间切换——负载均衡在工作。
验证服务下线感知
kill 掉 8082 实例(SIGTERM),再连续调用:
- 前 90 秒内:偶尔还有请求打到 8082(注册表里还在,客户端缓存也没更新),返回连接错误——因为有重试和超时,最终会切换到 8081
- 90 秒后:租约过期被剔除,增量拉取同步给 order-service,之后全部打到 8081
这个"前 90 秒有不均匀失败"的现象,就是前面反复强调的客户端必须配超时和重试的实证。
验证自我保护
把两个 user-service 都停掉,立刻看 Dashboard:保护模式大概率 ON(续约率归零),实例还在表里。这是预期行为,别慌。
五、RestTemplate 方式(不引入 Feign 的老项目)
存量项目可能不想动依赖,用 RestTemplate:
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced // 关键注解,开启客户端负载均衡
public RestTemplate restTemplate() {
return new RestTemplate();
}
}@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/orders/{id}")
public Object getById(@PathVariable Long id) {
// 服务名代替 IP:PORT
return restTemplate.getForObject(
"http://user-service/users/" + id, Object.class);
}
}@LoadBalanced 的 RestTemplate 会把 http://user-service 里的服务名解析成实例。注意 @LoadBalanced 是"全局生效"的——一个 RestTemplate 一旦标记,所有请求都走负载均衡,不存在"一半服务名一半真实地址"的混用。混用就定义两个 Bean。
六、多环境隔离
dev/test/prod 共用一个注册中心会互相污染。三种隔离方案:
方案一:多注册中心集群(最稳)。每环境一套 Eureka 集群,配置里 service-url 指向不同集群。资源换清晰。
方案二:同一集群 + 服务名带环境后缀(user-service-dev)。省资源,但服务名难看,且消费者配置要跟着环境变。
方案三:Eureka 的 namespace / region。Eureka 1.x 的 namespace 支持很弱(主要是 AWS Region 概念),不如方案一直接。
团队规模小选方案一,别纠结。
七、常见集成问题
Feign 调用报 Load balancer does not contain an instance for the service user-service 注册表里没这个服务。按顺序查:服务名拼写(大小写不敏感但连字符要对)、service-url 指没指对、提供者启动日志有没有注册成功、Dashboard 里有没有。
启动慢,日志卡在 DiscoveryClient ... waiting for registry 提供者在等注册中心响应。注册中心没起、或 service-url 配错。这个等待有超时,但会让启动慢几十秒,先起注册中心。
注册的 IP 是 127.0.0.1,别的机器连不上prefer-ip-address: true 配上,或者指定 ip-address。容器里尤其注意:容器内的 127.0.0.1 对外部无意义。
Actuator 健康检查让服务频繁 DOWN/UP 抖动 健康检查依赖的组件(DB、MQ)本身在抖,导致 /actuator/health 状态反复。把不稳定的组件从健康组里摘掉,只保留核心依赖:
management:
health:
db:
enabled: false小结
跑通这套,你就有了一个最小可用的微服务体系。几个生产强化点再强调一遍:
- Feign 或 RestTemplate 的超时和重试必须配,这是注册中心数据滞后的唯一兜底
- 健康检查开启,但要稳定,别把爱抖的组件放进去
- 多环境物理隔离注册中心,别混用
下一篇 配置项大全,把散落各篇的配置按场景汇总,方便查阅。
