Eureka服务端 #

一、Eureka概述 #

1.1 Eureka简介 #

Eureka是Netflix开源的服务发现组件,Spring Cloud将其集成到自己的生态中,作为服务注册中心使用。

text
┌─────────────────────────────────────────────────────────────┐
│                    Eureka架构图                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│                    ┌─────────────────┐                      │
│                    │  Eureka Server  │                      │
│                    │   (注册中心)     │                      │
│                    └────────┬────────┘                      │
│                             │                               │
│         ┌───────────────────┼───────────────────┐          │
│         │                   │                   │          │
│         ▼                   ▼                   ▼          │
│   ┌───────────┐       ┌───────────┐       ┌───────────┐   │
│   │ 服务实例A │       │ 服务实例B │       │ 服务实例C │   │
│   │ Provider  │       │ Consumer  │       │ Gateway   │   │
│   └───────────┘       └───────────┘       └───────────┘   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

1.2 Eureka核心概念 #

概念 说明
Eureka Server 注册中心服务器,提供服务注册和发现功能
Eureka Client 服务客户端,包括服务提供者和服务消费者
Service Provider 服务提供者,向Eureka注册自己的服务
Service Consumer 服务消费者,从Eureka获取服务列表
Application 应用名称,同一应用可能有多个实例
Instance 服务实例,一个应用的具体实例

1.3 Eureka特性 #

特性 说明
AP设计 优先保证可用性,允许数据不一致
自我保护 网络分区时保护服务注册信息
心跳机制 服务定时发送心跳保持注册状态
服务剔除 长时间未心跳的服务被自动剔除

二、快速开始 #

2.1 创建项目 #

创建Maven项目,添加依赖:

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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>eureka-server</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2023.0.0</spring-cloud.version>
    </properties>

    <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>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.2 创建启动类 #

java
package com.example.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

2.3 配置文件 #

创建 application.yml

yaml
server:
  port: 8761

spring:
  application:
    name: eureka-server

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

2.4 启动测试 #

bash
mvn spring-boot:run

访问 http://localhost:8761 查看Eureka控制台。

三、配置详解 #

3.1 服务端配置 #

yaml
eureka:
  server:
    enable-self-preservation: true
    eviction-interval-timer-in-ms: 60000
    renewal-percent-threshold: 0.85
    renewal-threshold-update-interval-ms: 15000
    peer-eureka-nodes-update-interval-ms: 600000
    wait-time-in-ms-when-sync-empty: 0
配置项 默认值 说明
enable-self-preservation true 是否开启自我保护模式
eviction-interval-timer-in-ms 60000 服务剔除间隔时间
renewal-percent-threshold 0.85 续约百分比阈值
renewal-threshold-update-interval-ms 15000 续约阈值更新间隔
peer-eureka-nodes-update-interval-ms 600000 集群节点更新间隔
wait-time-in-ms-when-sync-empty 0 同步为空时等待时间

3.2 实例配置 #

yaml
eureka:
  instance:
    hostname: localhost
    appname: eureka-server
    instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
    prefer-ip-address: false
    ip-address: 127.0.0.1
    lease-renewal-interval-in-seconds: 30
    lease-expiration-duration-in-seconds: 90
    status-page-url-path: /actuator/info
    health-check-url-path: /actuator/health
    home-page-url-path: /
配置项 默认值 说明
hostname localhost 主机名
appname unknown 应用名称
instance-id - 实例ID
prefer-ip-address false 是否优先使用IP
lease-renewal-interval-in-seconds 30 心跳间隔
lease-expiration-duration-in-seconds 90 过期时间

3.3 客户端配置(服务端作为客户端) #

yaml
eureka:
  client:
    enabled: true
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:8761/eureka/
    registry-fetch-interval-seconds: 30
    instance-info-replication-interval-seconds: 30
    initial-instance-info-replication-interval-seconds: 40
    eureka-service-url-poll-interval-seconds: 300
    eureka-server-read-timeout-seconds: 8
    eureka-server-connect-timeout-seconds: 5
配置项 默认值 说明
enabled true 是否启用Eureka客户端
register-with-eureka true 是否注册到Eureka
fetch-registry true 是否获取注册表
registry-fetch-interval-seconds 30 拉取注册表间隔

四、集群模式 #

4.1 集群架构 #

text
┌─────────────────────────────────────────────────────────────┐
│                    Eureka集群架构                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   ┌─────────────┐         ┌─────────────┐                  │
│   │ Eureka      │◄───────►│ Eureka      │                  │
│   │ Server A    │  复制    │ Server B    │                  │
│   │ :8761       │         │ :8762       │                  │
│   └──────┬──────┘         └──────┬──────┘                  │
│          │                       │                          │
│          │      ┌─────────────┐  │                          │
│          └─────►│ Eureka      │◄─┘                          │
│           复制  │ Server C    │                             │
│                 │ :8763       │                             │
│                 └─────────────┘                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

4.2 集群配置 #

节点A配置 (application-peer1.yml):

yaml
server:
  port: 8761

spring:
  application:
    name: eureka-server

eureka:
  instance:
    hostname: peer1
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://peer2:8762/eureka/,http://peer3:8763/eureka/

节点B配置 (application-peer2.yml):

yaml
server:
  port: 8762

spring:
  application:
    name: eureka-server

eureka:
  instance:
    hostname: peer2
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://peer1:8761/eureka/,http://peer3:8763/eureka/

节点C配置 (application-peer3.yml):

yaml
server:
  port: 8763

spring:
  application:
    name: eureka-server

eureka:
  instance:
    hostname: peer3
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://peer1:8761/eureka/,http://peer2:8762/eureka/

4.3 启动集群 #

bash
# 启动节点A
java -jar eureka-server.jar --spring.profiles.active=peer1

# 启动节点B
java -jar eureka-server.jar --spring.profiles.active=peer2

# 启动节点C
java -jar eureka-server.jar --spring.profiles.active=peer3

4.4 本地模拟集群 #

修改hosts文件:

text
127.0.0.1 peer1
127.0.0.1 peer2
127.0.0.1 peer3

五、自我保护机制 #

5.1 什么是自我保护 #

Eureka的自我保护机制是一种应对网络异常的安全措施。当Eureka Server在短时间内丢失过多客户端心跳时,会进入自我保护模式,不再剔除服务实例。

text
正常模式:
┌─────────────┐
│ Eureka      │
│ Server      │──► 心跳正常 ──► 保持注册
└─────────────┘
      │
      └──► 心跳超时 ──► 剔除实例

自我保护模式:
┌─────────────┐
│ Eureka      │
│ Server      │──► 心跳丢失 > 85% ──► 进入自我保护
└─────────────┘
      │
      ├──► 不再剔除实例
      └──► 保护现有注册信息

5.2 自我保护触发条件 #

text
触发条件:
实际续约数 < 期望续约数 * 续约百分比阈值(默认0.85)

期望续约数 = 注册实例数 * 2 (每分钟)
实际续约数 = 实际收到的心跳数

5.3 自我保护配置 #

yaml
eureka:
  server:
    enable-self-preservation: true
    renewal-percent-threshold: 0.85

5.4 开发环境关闭自我保护 #

开发环境建议关闭自我保护,便于调试:

yaml
eureka:
  server:
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 5000

六、安全认证 #

6.1 添加安全依赖 #

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

6.2 配置安全认证 #

yaml
spring:
  security:
    user:
      name: admin
      password: admin123

eureka:
  client:
    service-url:
      defaultZone: http://admin:admin123@localhost:8761/eureka/

6.3 安全配置类 #

java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.ignoringRequestMatchers("/eureka/**"))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/eureka/**").authenticated()
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

七、监控与管理 #

7.1 添加Actuator依赖 #

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

7.2 配置Actuator #

yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,env
  endpoint:
    health:
      show-details: always

7.3 健康检查端点 #

bash
# 健康检查
curl http://localhost:8761/actuator/health

# 返回示例
{
  "status": "UP",
  "components": {
    "discoveryComposite": {
      "status": "UP"
    },
    "diskSpace": {
      "status": "UP"
    },
    "eureka": {
      "status": "UP"
    },
    "ping": {
      "status": "UP"
    }
  }
}

八、最佳实践 #

8.1 生产环境配置 #

yaml
server:
  port: 8761

spring:
  application:
    name: eureka-server

eureka:
  server:
    enable-self-preservation: true
    eviction-interval-timer-in-ms: 60000
    renewal-percent-threshold: 0.85
    
  instance:
    hostname: ${HOSTNAME:eureka-server}
    prefer-ip-address: true
    lease-renewal-interval-in-seconds: 30
    lease-expiration-duration-in-seconds: 90
    
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: ${EUREKA_SERVER_URL:http://localhost:8761/eureka/}
    registry-fetch-interval-seconds: 30

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      show-details: when-authorized

8.2 JVM参数优化 #

bash
java -jar eureka-server.jar \
  -Xms512m \
  -Xmx1024m \
  -XX:+UseG1GC \
  -XX:MaxGCPauseMillis=200 \
  -XX:+HeapDumpOnOutOfMemoryError \
  -XX:HeapDumpPath=/logs/heapdump.hprof

8.3 注意事项 #

注意点 说明
集群节点数 建议奇数个,至少3个
网络延迟 节点间网络延迟应小于200ms
数据一致性 Eureka是AP系统,不保证强一致性
服务剔除 自我保护模式下不会剔除服务

九、常见问题 #

9.1 服务注册不上 #

排查步骤:

  1. 检查网络连通性
  2. 检查配置的service-url是否正确
  3. 检查是否有安全认证
  4. 查看Eureka Server日志

9.2 集群同步失败 #

排查步骤:

  1. 检查hostname配置
  2. 检查端口是否开放
  3. 检查service-url配置是否正确

9.3 自我保护触发频繁 #

解决方案:

  1. 检查服务心跳配置
  2. 调整续约百分比阈值
  3. 检查网络稳定性

十、总结 #

10.1 核心要点 #

要点 说明
Eureka Server 服务注册中心
自我保护 网络异常时保护注册信息
集群模式 多节点高可用部署
安全认证 保护注册中心访问

10.2 下一步 #

现在你已经掌握了Eureka服务端的搭建,接下来让我们学习 Eureka客户端,实现服务的注册与发现!

最后更新:2026-03-28