Eureka入门教程 - Spring Cloud服务发现框架完整指南
Eureka入门教程 - Spring Cloud服务发现框架完整指南
目录
- Eureka简介
- 环境准备
- Eureka Server搭建
- Eureka Client配置
- 服务注册与发现
- Eureka高可用配置
- Eureka配置详解
- Eureka监控与运维
- Eureka与Spring Cloud集成
- 实际应用案例
- 常见问题与解决方案
- 最佳实践
- 总结与进阶
1. Eureka简介
Eureka是Netflix开发的服务发现框架,是Spring Cloud生态系统中的核心组件之一。Eureka提供了服务注册与发现的能力,使得微服务架构中的服务可以自动发现和调用其他服务。
Eureka Server(Eureka服务器)
- 服务注册中心,提供服务注册和发现功能
- 维护所有注册服务的元数据信息
- 提供RESTful API供客户端查询服务信息
Eureka Client(Eureka客户端)
- 服务提供者:向Eureka Server注册自己的服务信息
- 服务消费者:从Eureka Server获取服务列表,实现服务调用
服务注册(Service Registration)
- 服务启动时向Eureka Server注册自己的信息
- 包括服务名、IP地址、端口号等
服务发现(Service Discovery)
- 客户端从Eureka Server获取服务列表
- 根据服务名找到对应的服务实例
心跳机制(Heartbeat)
- 客户端定期向Eureka Server发送心跳
- 证明服务实例仍然存活
服务续约(Renewal)
客户端定期更新注册信息
保持服务注册信息的有效性
✅ 简单易用:配置简单,上手快
✅ 高可用:支持集群部署
✅ 自动发现:服务自动注册和发现
✅ 健康检查:自动检测服务状态
✅ 负载均衡:集成Ribbon实现负载均衡
✅ Spring Cloud集成:与Spring Cloud无缝集成
┌─────────────────┐
│ Eureka Server │ ← 服务注册中心
│ (注册中心) │
└────────┬────────┘
│
┌────┴────┐
│ │
┌───▼───┐ ┌──▼────┐
│Service│ │Service│ ← 服务提供者(Eureka Client)
│ A │ │ B │
└───┬───┘ └──┬────┘
│ │
└────┬───┘
│
┌────▼────┐
│Consumer │ ← 服务消费者(Eureka Client)
│Service │
└─────────┘| 特性 | Eureka | Consul | Zookeeper | Nacos |
|---|---|---|---|---|
| 开发公司 | Netflix | HashiCorp | Apache | Alibaba |
| 语言 | Java | Go | Java | Java |
| 一致性 | AP | CP | CP | AP/CP |
| 健康检查 | 客户端心跳 | 多种方式 | 会话 | 多种方式 |
| 配置管理 | 否 | 是 | 否 | 是 |
| Spring Cloud集成 | 原生支持 | 支持 | 支持 | 原生支持 |
2. 环境准备
- JDK:JDK 8或更高版本(推荐JDK 11+)
- Maven:3.6+ 或 Gradle 6+
- IDE:IntelliJ IDEA、Eclipse等
- Spring Boot:2.x 或 3.x
- Spring Cloud:2020.x 或更高版本
推荐的项目结构:
microservices-demo/
├── eureka-server/ # Eureka Server项目
│ ├── src/
│ └── pom.xml
├── service-provider/ # 服务提供者
│ ├── src/
│ └── pom.xml
├── service-consumer/ # 服务消费者
│ ├── src/
│ └── pom.xml
└── pom.xml # 父POM创建父项目的pom.xml:
<?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>microservices-demo</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>2.7.18</spring-boot.version>
<spring-cloud.version>2021.0.9</spring-cloud.version>
</properties>
<modules>
<module>eureka-server</module>
<module>service-provider</module>
<module>service-consumer</module>
</modules>
<dependencyManagement>
<dependencies>
<!-- Spring Boot依赖管理 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud依赖管理 -->
<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>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>3. Eureka Server搭建
步骤1:创建Maven模块
在父项目下创建eureka-server模块。
步骤2:添加依赖
编辑eureka-server/pom.xml:
<?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>
<parent>
<groupId>com.example</groupId>
<artifactId>microservices-demo</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>eureka-server</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Eureka Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>创建EurekaServerApplication.java:
package com.example.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* Eureka Server启动类
*/
@SpringBootApplication
@EnableEurekaServer // 启用Eureka Server
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}关键注解说明:
@SpringBootApplication:Spring Boot应用注解@EnableEurekaServer:启用Eureka Server功能
创建application.yml:
server:
port: 8761 # Eureka Server端口
spring:
application:
name: eureka-server
eureka:
instance:
hostname: localhost
client:
# 不向自己注册
register-with-eureka: false
# 不从自己获取服务注册信息
fetch-registry: false
service-url:
# Eureka Server的地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/方式1:使用IDE启动
- 右键点击
EurekaServerApplication.java - 选择"Run 'EurekaServerApplication'"
- 等待启动完成
方式2:使用Maven命令
cd eureka-server
mvn spring-boot:run方式3:打包后运行
mvn clean package
java -jar target/eureka-server-1.0.0.jar启动成功后,访问:http://localhost:8761
你会看到Eureka的控制台界面,显示:
- Instances currently registered with Eureka:当前注册的服务实例
- General Info:Eureka Server的一般信息
- DS Replicas:Eureka Server的副本信息
4. Eureka Client配置
步骤1:创建Maven模块
创建service-provider模块。
步骤2:添加依赖
编辑service-provider/pom.xml:
<?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>
<parent>
<groupId>com.example</groupId>
<artifactId>microservices-demo</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>service-provider</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- Spring Boot Starter 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>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>步骤3:创建启动类
创建ServiceProviderApplication.java:
package com.example.serviceprovider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* 服务提供者启动类
*/
@SpringBootApplication
@EnableEurekaClient // 启用Eureka Client
public class ServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class, args);
}
}注意: Spring Cloud 2020.x版本后,@EnableEurekaClient可以省略,只要添加了spring-cloud-starter-netflix-eureka-client依赖即可。
步骤4:配置文件
创建application.yml:
server:
port: 8081 # 服务端口
spring:
application:
name: service-provider # 服务名称,用于服务发现
eureka:
client:
service-url:
# Eureka Server地址
defaultZone: http://localhost:8761/eureka/
# 是否注册到Eureka
register-with-eureka: true
# 是否从Eureka获取服务注册信息
fetch-registry: 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步骤5:创建Controller
创建HelloController.java:
package com.example.serviceprovider.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Hello Controller
*/
@RestController
@RequestMapping("/api")
public class HelloController {
@Value("${server.port}")
private String port;
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
return String.format("Hello %s, this is service-provider on port %s", name, port);
}
@GetMapping("/info")
public String info() {
return "Service Provider Info: " + port;
}
}步骤1:创建Maven模块
创建service-consumer模块。
步骤2:添加依赖
编辑service-consumer/pom.xml:
<?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>
<parent>
<groupId>com.example</groupId>
<artifactId>microservices-demo</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>service-consumer</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- Spring Boot Starter 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>
<!-- Ribbon负载均衡 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<!-- RestTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>步骤3:创建启动类
创建ServiceConsumerApplication.java:
package com.example.serviceconsumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* 服务消费者启动类
*/
@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现
public class ServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class, args);
}
/**
* 创建RestTemplate Bean,并启用负载均衡
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}步骤4:配置文件
创建application.yml:
server:
port: 8082
spring:
application:
name: service-consumer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: true
fetch-registry: true
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${server.port}步骤5:创建Controller
创建ConsumerController.java:
package com.example.serviceconsumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* 服务消费者Controller
*/
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
/**
* 使用RestTemplate调用服务提供者
*/
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
// 使用服务名调用,Ribbon会自动负载均衡
String url = "http://service-provider/api/hello/" + name;
return restTemplate.getForObject(url, String.class);
}
/**
* 获取服务实例信息
*/
@GetMapping("/instances")
public List<ServiceInstance> getInstances() {
return discoveryClient.getInstances("service-provider");
}
/**
* 获取所有服务
*/
@GetMapping("/services")
public List<String> getServices() {
return discoveryClient.getServices();
}
}5. 服务注册与发现
服务启动:服务提供者启动
注册请求:向Eureka Server发送注册请求
信息存储:Eureka Server存储服务信息
心跳维持:定期发送心跳保持注册
获取服务列表:消费者从Eureka Server获取服务列表
缓存本地:将服务列表缓存到本地
定期更新:定期从Eureka Server更新服务列表
负载均衡:使用Ribbon进行负载均衡
步骤1:启动Eureka Server
cd eureka-server
mvn spring-boot:run访问 http://localhost:8761 查看控制台。
步骤2:启动服务提供者
cd service-provider
mvn spring-boot:run在Eureka控制台可以看到service-provider已注册。
步骤3:启动服务消费者
cd service-consumer
mvn spring-boot:run步骤4:测试服务调用
# 调用消费者接口
curl http://localhost:8082/consumer/hello/World
# 查看服务实例
curl http://localhost:8082/consumer/instances
# 查看所有服务
curl http://localhost:8082/consumer/services启动多个服务提供者实例
# 实例1:端口8081
java -jar service-provider.jar --server.port=8081
# 实例2:端口8083
java -jar service-provider.jar --server.port=8083
# 实例3:端口8084
java -jar service-provider.jar --server.port=8084在Eureka控制台可以看到多个service-provider实例。
测试负载均衡
多次调用消费者接口:
curl http://localhost:8082/consumer/hello/World可以看到请求被分发到不同的服务实例。
6. Eureka高可用配置
配置多个Eureka Server
application-peer1.yml:
server:
port: 8761
spring:
application:
name: eureka-server
eureka:
instance:
hostname: peer1
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://peer2:8762/eureka/,http://peer3:8763/eureka/application-peer2.yml:
server:
port: 8762
spring:
application:
name: eureka-server
eureka:
instance:
hostname: peer2
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://peer1:8761/eureka/,http://peer3:8763/eureka/application-peer3.yml:
server:
port: 8763
spring:
application:
name: eureka-server
eureka:
instance:
hostname: peer3
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://peer1:8761/eureka/,http://peer2:8762/eureka/配置hosts文件
编辑/etc/hosts(Linux/macOS)或C:\Windows\System32\drivers\etc\hosts(Windows):
127.0.0.1 peer1
127.0.0.1 peer2
127.0.0.1 peer3启动Eureka Server集群
# 启动peer1
java -jar eureka-server.jar --spring.profiles.active=peer1
# 启动peer2
java -jar eureka-server.jar --spring.profiles.active=peer2
# 启动peer3
java -jar eureka-server.jar --spring.profiles.active=peer3更新客户端的application.yml:
eureka:
client:
service-url:
# 配置多个Eureka Server地址
defaultZone: http://peer1:8761/eureka/,http://peer2:8762/eureka/,http://peer3:8763/eureka/7. Eureka配置详解
完整配置示例
server:
port: 8761
spring:
application:
name: eureka-server
eureka:
instance:
hostname: localhost
# 续约间隔(秒)
lease-renewal-interval-in-seconds: 30
# 服务失效时间(秒)
lease-expiration-duration-in-seconds: 90
server:
# 是否开启自我保护机制
enable-self-preservation: true
# 清理间隔(毫秒)
eviction-interval-timer-in-ms: 60000
# 续约阈值百分比
renewal-percent-threshold: 0.85
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
# 注册中心连接超时时间(秒)
eureka-connection-idle-timeout-seconds: 30
# 注册中心读取超时时间(秒)
eureka-read-timeout-seconds: 8完整配置示例
eureka:
client:
# 是否注册到Eureka
register-with-eureka: true
# 是否从Eureka获取服务注册信息
fetch-registry: true
# Eureka Server地址
service-url:
defaultZone: http://localhost:8761/eureka/
# 注册中心连接超时时间(秒)
eureka-connection-idle-timeout-seconds: 30
# 注册中心读取超时时间(秒)
eureka-read-timeout-seconds: 8
# 注册中心连接池大小
eureka-connection-pool-size: 5
# 注册中心健康检查
healthcheck:
enabled: true
instance:
# 使用IP地址注册
prefer-ip-address: true
# 实例ID
instance-id: ${spring.application.name}:${server.port}
# 主机名
hostname: localhost
# 续约间隔(秒)
lease-renewal-interval-in-seconds: 30
# 服务失效时间(秒)
lease-expiration-duration-in-seconds: 90
# 状态页面URL路径
status-page-url-path: /actuator/info
# 健康检查URL路径
health-check-url-path: /actuator/health
# 主页URL路径
home-page-url-path: /Eureka的自我保护机制是为了防止网络分区故障导致服务被误删。
工作原理:
- 当Eureka Server在短时间内丢失过多客户端时,会进入自我保护模式
- 在自我保护模式下,Eureka Server不会删除服务注册信息
- 等待网络恢复后,自动退出自我保护模式
配置:
eureka:
server:
# 是否开启自我保护(默认true)
enable-self-preservation: true
# 续约阈值百分比(默认0.85)
renewal-percent-threshold: 0.858. Eureka监控与运维
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>配置Actuator
management:
endpoints:
web:
exposure:
include: "*" # 暴露所有端点
endpoint:
health:
show-details: always访问监控端点
- 健康检查:http://localhost:8761/actuator/health
- 服务信息:http://localhost:8761/actuator/info
- 所有端点:http://localhost:8761/actuator
Eureka提供了RESTful API用于查询和管理服务。
查询所有服务
GET http://localhost:8761/eureka/apps查询特定服务
GET http://localhost:8761/eureka/apps/{service-name}查询服务实例
GET http://localhost:8761/eureka/apps/{service-name}/{instance-id}下线服务实例
DELETE http://localhost:8761/eureka/apps/{service-name}/{instance-id}配置logback
创建logback-spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.netflix.eureka" level="INFO"/>
<logger name="com.netflix.discovery" level="INFO"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>9. Eureka与Spring Cloud集成
Ribbon是客户端负载均衡器,与Eureka无缝集成。
配置Ribbon
service-provider:
ribbon:
# 连接超时时间(毫秒)
ConnectTimeout: 1000
# 读取超时时间(毫秒)
ReadTimeout: 3000
# 最大重试次数
MaxAutoRetries: 1
# 最大重试下一个服务器的次数
MaxAutoRetriesNextServer: 2
# 是否对所有操作都重试
OkToRetryOnAllOperations: falseFeign是声明式HTTP客户端,简化服务调用。
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>启用Feign
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 启用Feign
public class ServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class, args);
}
}创建Feign客户端
@FeignClient(name = "service-provider")
public interface ServiceProviderClient {
@GetMapping("/api/hello/{name}")
String hello(@PathVariable String name);
@GetMapping("/api/info")
String info();
}使用Feign客户端
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@Autowired
private ServiceProviderClient serviceProviderClient;
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
return serviceProviderClient.hello(name);
}
}Spring Cloud Gateway可以与Eureka集成实现API网关。
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>配置Gateway
spring:
cloud:
gateway:
routes:
- id: service-provider
uri: lb://service-provider # 使用lb://协议,自动负载均衡
predicates:
- Path=/api/**
filters:
- StripPrefix=110. 实际应用案例
┌─────────────┐
│ Eureka │
│ Server │
└──────┬──────┘
│
┌───┴────┬──────────┬──────────┐
│ │ │ │
┌──▼──┐ ┌──▼──┐ ┌──▼──┐ ┌──▼──┐
│User │ │Order│ │Pay │ │Goods│
│Service│ │Service│ │Service│ │Service│
└──────┘ └──────┘ └──────┘ └──────┘// 订单服务调用用户服务和商品服务
@Service
public class OrderService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private UserServiceClient userServiceClient;
@Autowired
private GoodsServiceClient goodsServiceClient;
public Order createOrder(Long userId, Long goodsId) {
// 调用用户服务
User user = userServiceClient.getUser(userId);
// 调用商品服务
Goods goods = goodsServiceClient.getGoods(goodsId);
// 创建订单
Order order = new Order();
order.setUserId(userId);
order.setGoodsId(goodsId);
order.setAmount(goods.getPrice());
return orderRepository.save(order);
}
}11. 常见问题与解决方案
问题: 服务启动后无法注册到Eureka Server
解决方案:
- 检查Eureka Server是否启动
- 检查
eureka.client.service-url.defaultZone配置是否正确 - 检查网络连接
- 查看日志错误信息
问题: 无法从Eureka获取服务列表
解决方案:
- 检查
eureka.client.fetch-registry是否为true - 检查服务是否已注册
- 检查Eureka Server连接
- 清除本地缓存
问题: Eureka进入自我保护模式,服务被标记为DOWN
解决方案:
- 检查网络连接
- 检查服务心跳是否正常
- 临时关闭自我保护:
eureka.server.enable-self-preservation=false - 调整续约阈值
问题: 请求总是路由到同一个服务实例
解决方案:
- 检查是否添加了
@LoadBalanced注解 - 检查Ribbon配置
- 清除Ribbon缓存
- 检查服务实例是否都正常注册
12. 最佳实践
生产环境配置
- 启用自我保护机制
- 配置合理的续约间隔
- 使用集群部署Eureka Server
服务配置
- 使用IP地址注册
- 配置合理的超时时间
- 启用健康检查
监控配置
- 集成Actuator
- 配置日志级别
- 监控服务注册状态
减少注册中心压力
- 合理设置心跳间隔
- 使用本地缓存
- 减少不必要的查询
提高可用性
- Eureka Server集群部署
- 客户端配置多个Server地址
- 启用健康检查
认证授权
- 使用Spring Security保护Eureka Server
- 配置HTTPS
- 限制访问IP
网络安全
- 使用内网通信
- 配置防火墙规则
- 使用VPN或专线
13. 总结与进阶
通过本教程,你已经掌握了:
- ✅ Eureka的基本概念和架构
- ✅ Eureka Server的搭建和配置
- ✅ Eureka Client的配置和使用
- ✅ 服务注册与发现的流程
- ✅ Eureka高可用配置
- ✅ 与Spring Cloud其他组件的集成
源码学习
- Eureka Server源码分析
- Eureka Client源码分析
- 服务注册与发现机制
性能优化
- 注册中心性能优化
- 服务发现性能优化
- 网络优化
替代方案
- Consul服务发现
- Nacos服务发现
- Zookeeper服务发现
微服务架构
- 服务网关
- 配置中心
- 服务监控
- 分布式追踪
Spring Cloud文档:https://spring.io/projects/spring-cloud
Spring Cloud Netflix:https://spring.io/projects/spring-cloud-netflix
⚠️ Eureka 2.x已停止开发,建议使用1.x版本
⚠️ Spring Cloud 2020.x后,Eureka进入维护模式
✅ 新项目建议考虑Nacos或Consul
✅ 现有项目可以继续使用Eureka
结语
Eureka是Spring Cloud微服务架构中的重要组件,提供了强大的服务注册与发现能力。通过本教程的学习,相信你已经掌握了Eureka的核心功能和使用方法。
记住:
- 多实践:通过实际项目加深理解
- 关注更新:关注Spring Cloud和Eureka的发展
- 理解原理:深入理解服务发现的机制
- 持续学习:学习微服务架构的其他组件
祝你学习愉快,编程顺利! 🚀
本教程由Java突击队学习社区编写,如有问题欢迎反馈。