Eureka Client使用
2026/1/15大约 4 分钟EurekaEureka Client服务注册
Eureka Client 使用
一、服务提供者
1.1 创建项目
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>user-service</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
</properties>
<dependencies>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Eureka Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>1.2 启动类
package com.example.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现(可省略,自动配置)
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}1.3 配置文件
server:
port: 8081
spring:
application:
name: user-service # 服务名称,必须配置
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
# 使用 IP 地址注册
prefer-ip-address: true
# 自定义实例 ID
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}1.4 提供接口
@RestController
@RequestMapping("/user")
public class UserController {
@Value("${server.port}")
private String port;
@GetMapping("/{id}")
public Map<String, Object> getUser(@PathVariable Long id) {
Map<String, Object> user = new HashMap<>();
user.put("id", id);
user.put("name", "张三");
user.put("port", port);
return user;
}
@GetMapping("/list")
public List<Map<String, Object>> listUsers() {
List<Map<String, Object>> users = new ArrayList<>();
// 模拟数据
for (int i = 1; i <= 5; i++) {
Map<String, Object> user = new HashMap<>();
user.put("id", i);
user.put("name", "用户" + i);
users.add(user);
}
return users;
}
}二、服务消费者
2.1 创建项目
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>2.2 配置文件
server:
port: 8082
spring:
application:
name: order-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true2.3 配置 RestTemplate
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced // 启用负载均衡
public RestTemplate restTemplate() {
return new RestTemplate();
}
}2.4 调用服务
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{id}")
public Map<String, Object> getOrder(@PathVariable Long id) {
// 使用服务名调用(不是 IP:端口)
String url = "http://user-service/user/" + id;
Map<String, Object> user = restTemplate.getForObject(url, Map.class);
Map<String, Object> order = new HashMap<>();
order.put("orderId", id);
order.put("orderNo", "ORDER" + System.currentTimeMillis());
order.put("user", user);
return order;
}
}三、服务调用流程
四、使用 DiscoveryClient
4.1 获取服务实例信息
@RestController
@RequestMapping("/discovery")
public class DiscoveryController {
@Autowired
private DiscoveryClient discoveryClient;
/**
* 获取所有服务名称
*/
@GetMapping("/services")
public List<String> getServices() {
return discoveryClient.getServices();
}
/**
* 获取指定服务的所有实例
*/
@GetMapping("/instances/{serviceName}")
public List<ServiceInstance> getInstances(@PathVariable String serviceName) {
return discoveryClient.getInstances(serviceName);
}
/**
* 手动选择实例调用
*/
@GetMapping("/call/{serviceName}")
public String callService(@PathVariable String serviceName) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
if (instances.isEmpty()) {
return "No instances available";
}
// 简单轮询选择第一个实例
ServiceInstance instance = instances.get(0);
String url = instance.getUri() + "/user/1";
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(url, String.class);
}
}4.2 ServiceInstance 信息
| 属性 | 说明 |
|---|---|
serviceId | 服务名称 |
host | 主机地址 |
port | 端口号 |
uri | 完整 URI |
metadata | 元数据 |
secure | 是否 HTTPS |
五、元数据配置
5.1 配置元数据
eureka:
instance:
metadata-map:
version: v1.0
region: beijing
weight: 105.2 读取元数据
@GetMapping("/metadata/{serviceName}")
public List<Map<String, String>> getMetadata(@PathVariable String serviceName) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
return instances.stream()
.map(ServiceInstance::getMetadata)
.collect(Collectors.toList());
}六、健康检查配置
6.1 添加 Actuator 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>6.2 配置健康检查
eureka:
client:
# 启用健康检查
healthcheck:
enabled: true
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: always七、多实例部署
7.1 启动多个实例
# 启动实例1
java -jar user-service.jar --server.port=8081
# 启动实例2
java -jar user-service.jar --server.port=8082
# 启动实例3
java -jar user-service.jar --server.port=80837.2 IDEA 多实例配置
- 复制启动配置
- 修改 VM Options:
-Dserver.port=8082 - 启动多个实例
八、常见配置汇总
eureka:
client:
# 是否注册到 Eureka
register-with-eureka: true
# 是否获取注册表
fetch-registry: true
# Eureka Server 地址
service-url:
defaultZone: http://localhost:8761/eureka/
# 获取注册表间隔(秒)
registry-fetch-interval-seconds: 30
# 启用健康检查
healthcheck:
enabled: true
instance:
# 使用 IP 注册
prefer-ip-address: true
# 实例 ID
instance-id: ${spring.application.name}:${server.port}
# 心跳间隔(秒)
lease-renewal-interval-in-seconds: 30
# 服务过期时间(秒)
lease-expiration-duration-in-seconds: 90
# 元数据
metadata-map:
version: v1.0九、总结
本章介绍了 Eureka Client 的使用:
- 服务提供者:注册服务到 Eureka Server
- 服务消费者:从 Eureka 获取服务列表并调用
- DiscoveryClient:手动获取服务实例信息
- 元数据:自定义服务元信息
- 健康检查:配置服务健康状态上报
