云计算百科
云计算领域专业知识百科平台

服务发现:Eureka 服务器(Service Discovery: Eureka Server)

构建 Spring Cloud Eureka Server 注册中心

一、目标

创建一个独立的 Spring Cloud Eureka Server,作为微服务架构的服务注册与发现中心。

二、官方文档

Spring Cloud 主页

https://spring.io/projects/spring-cloud

Eureka Server 官方文档

服务发现:Eureka 服务器(Service Discovery: Eureka Server): https://docs.spring.io/spring-cloud-netflix/reference/spring-cloud-netflix.html#spring-cloud-eureka-server

如何包含 Eureka 服务器

要在项目中包含 Eureka Server,请使用 group ID 为 org.springframework.cloud 、artifact ID 为 spring-cloud-starter-netflix-eureka-server 的 starter。

如何运行 Eureka 服务器

注意:@EnableEurekaServer 注解。

单机模式(独立模式)

application.yml (独立 Eureka 服务器)

# application.yml (独立 Eureka 服务器)
server:
port: 8761

eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

高可用模式(Peer Awareness)

application.yml (两个相互感知的 Eureka 服务器)

# application.yml (两个相互感知的 Eureka 服务器)
# —
spring:
profiles: peer1
eureka:
instance:
hostname: peer1
client:
serviceUrl:
defaultZone: https://peer2/eureka/

# —
spring:
profiles: peer2
eureka:
instance:
hostname: peer2
client:
serviceUrl:
defaultZone: https://peer1/eureka/

application.yml (三个相互感知的 Eureka 服务器)

# application.yml (三个相互感知的 Eureka 服务器)
eureka:
client:
serviceUrl:
defaultZone: https://peer1/eureka/,http://peer2/eureka/,http://peer3/eureka/

# —
spring:
profiles: peer1
eureka:
instance:
hostname: peer1

# —
spring:
profiles: peer2
eureka:
instance:
hostname: peer2

# —
spring:
profiles: peer3
eureka:
instance:
hostname: peer3

使用 Eureka 服务器进行身份验证

URL 包含凭证(curl 风格,如下所示: user:password@localhost:8761/eureka )

三、创建 Spring Boot 项目

技术栈

  • Java (JDK): 21
  • Spring Boot: 3.5.3
  • Spring Cloud Netflix Eureka Server: 2025.0.0 (spring-cloud-starter-netflix-eureka-server)

项目创建方式

推荐使用 Spring Initializr 。

  • 选择项目类型:Maven
  • 选择语言:Java
  • 填写 Group, Artifact (如 com.example.hello, hello-eureka-server)
  • 选择 Spring Boot 版本:3.5.3
  • 添加依赖:Eureka Server

创建项目截图 图示:在项目创建工具中选择 Eureka Server 依赖。

四、项目配置

1. 配置 POM 文件 (pom.xml)

确保 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 https://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.5.3</version>
<relativePath/>
</parent>

<groupId>com.example.hello</groupId>
<artifactId>hello-eureka-server</artifactId>
<version>1.0.0</version>
<name>hello-eureka-server</name>
<description>Eureka注册中心服务器</description>

<properties>
<java.version>21</java.version>
<spring-cloud.version>2025.0.0</spring-cloud.version>
</properties>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>

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

</project>

2. 配置应用属性 (application.yml)

在 src/main/resources/application.yml 中添加 Eureka Server 配置:

spring:
application:
name: helloeurekaserver

server:
port: 8761 # Eureka Server默认端口

eureka:
instance:
# 设置Eureka Server的主机名
hostname: localhost
client:
# 关键配置:禁止 Eureka Server 将自己注册到注册中心(避免自注册)
register-with-eureka: false
# 关键配置:禁止 Eureka Server 从注册中心获取注册表信息(单机模式下不需要)
fetch-registry: false
service-url:
# 指定 Eureka Server 的访问地址。
# ${eureka.instance.hostname} 和 ${server.port} 引用上面的配置。
# 在集群模式下,这里会配置其他 Eureka Server 节点的地址。
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

关键配置解释
  • register-with-eureka:指示此实例是否应向 Eureka 服务器注册其信息以供其他人发现。在某些情况下,您不希望自己的实例被发现,而只想发现其他实例。默认值为 true。
  • fetch-registry:指示此客户端是否应从尤里卡服务器获取 Eureka 注册表信息。默认值为 true。
  • defaultZone:客户端(其他微服务)用来注册和发现服务的地址。单机模式下指向自己。
源代码(EurekaClientConfigBean,EurekaConstants)

/**
* Indicates whether or not this instance should register its information with eureka
* server for discovery by others.
*
* In some cases, you do not want your instances to be discovered whereas you just
* want do discover other instances.
*/

private boolean registerWithEureka = true;

/**
* Indicates whether this client should fetch eureka registry information from eureka
* server.
*/

private boolean fetchRegistry = true;

/**
* Map of availability zone to list of fully qualified URLs to communicate with eureka
* server. Each value can be a single URL or a comma separated list of alternative
* locations.
*
* Typically the eureka server URLs carry protocol,host,port,context and version
* information if any. Example:
* https://ec2-256-156-243-129.compute-1.amazonaws.com:7001/eureka/
*
* The changes are effective at runtime at the next service url refresh cycle as
* specified by eurekaServiceUrlPollIntervalSeconds.
*/

private Map<String, String> serviceUrl = new HashMap<>();

{
this.serviceUrl.put(DEFAULT_ZONE, DEFAULT_URL);
}

/**
* Default availability zone if none is resolved based on region.
*/

public static final String DEFAULT_ZONE = "defaultZone";

/**
* Default Eureka URL.
*/

public static final String DEFAULT_URL = "http://localhost:8761" + DEFAULT_PREFIX + "/";

/**
* Default Eureka prefix.
*/

public static final String DEFAULT_PREFIX = "/eureka";

官方文档说明

defaultZone 属性区分大小写,需要使用驼峰命名法,因为 serviceUrl 属性是一个 Map<String, String> 。因此, defaultZone 属性不遵循 Spring Boot 的常规蛇形命名法 default-zone 。

五、编写启动类

在 Spring Boot 主应用类上添加 @EnableEurekaServer 注解,激活 Eureka Server 功能。

package com.example.hello.eureka.server;

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

@EnableEurekaServer // 核心注解:启用 Eureka Server 功能
@SpringBootApplication
public class HelloEurekaServerApplication {

public static void main(String[] args) {
SpringApplication.run(HelloEurekaServerApplication.class, args);
}

}

六、启动 Eureka Server

运行 HelloEurekaServerApplication 的 main 方法启动服务器。

关键启动日志分析

启动过程中,注意观察以下关键日志信息,确认服务启动成功且配置生效:

. ____ _ __ _ _
/\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\
\\\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\\__, | / / / /
=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v3.5.3)

2025-06-22T11:00:19.834+08:00 INFO 4240 — [hello-eureka-server] [ main] c.e.h.e.s.HelloEurekaServerApplication : Starting HelloEurekaServerApplication using Java 21.0.1 with PID 4240 (E:\\hello-world\\hello-eureka-server\\target\\classes started by SongGuanxun in E:\\hello-world\\hello-eureka-server)
2025-06-22T11:00:19.842+08:00 INFO 4240 — [hello-eureka-server] [ main] c.e.h.e.s.HelloEurekaServerApplication : No active profile set, falling back to 1 default profile: "default"
2025-06-22T11:00:24.548+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=8a66a792-6a96-32b9-b70c-573fd48e1799
2025-06-22T11:00:26.372+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8761 (http)
2025-06-22T11:00:26.506+08:00 INFO 4240 — [hello-eureka-server] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2025-06-22T11:00:26.508+08:00 INFO 4240 — [hello-eureka-server] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.42]
2025-06-22T11:00:26.707+08:00 INFO 4240 — [hello-eureka-server] [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2025-06-22T11:00:26.711+08:00 INFO 4240 — [hello-eureka-server] [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 6658 ms
2025-06-22T11:00:30.462+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2025-06-22T11:00:30.466+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2025-06-22T11:00:31.415+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2025-06-22T11:00:31.415+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2025-06-22T11:00:32.018+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.v.b.OptionalValidatorFactoryBean : Failed to set up a Bean Validation provider: jakarta.validation.NoProviderFoundException: Unable to create a Configuration, because no Jakarta Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
2025-06-22T11:00:34.896+08:00 WARN 4240 — [hello-eureka-server] [ main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2025-06-22T11:00:34.968+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2025-06-22T11:00:35.112+08:00 INFO 4240 — [hello-eureka-server] [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2025-06-22T11:00:35.112+08:00 INFO 4240 — [hello-eureka-server] [ main] com.netflix.discovery.DiscoveryClient : Client configured to neither register nor query for data.
2025-06-22T11:00:35.132+08:00 INFO 4240 — [hello-eureka-server] [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1750561235121 with initial instances count: 0
2025-06-22T11:00:35.401+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.eureka.DefaultEurekaServerContext : Initializing …
2025-06-22T11:00:35.406+08:00 WARN 4240 — [hello-eureka-server] [ main] c.n.eureka.cluster.PeerEurekaNodes : The replica size seems to be empty. Check the route 53 DNS Registry
2025-06-22T11:00:35.440+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.e.registry.AbstractInstanceRegistry : Finished initializing remote region registries. All known remote regions: []
2025-06-22T11:00:35.440+08:00 INFO 4240 — [hello-eureka-server] [ main] c.n.eureka.DefaultEurekaServerContext : Initialized
2025-06-22T11:00:35.469+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint beneath base path '/actuator'
2025-06-22T11:00:35.647+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.c.n.e.s.EurekaServiceRegistry : Registering application HELLO-EUREKA-SERVER with eureka with status UP
2025-06-22T11:00:35.702+08:00 INFO 4240 — [hello-eureka-server] [ Thread-9] o.s.c.n.e.server.EurekaServerBootstrap : isAws returned false
2025-06-22T11:00:35.704+08:00 INFO 4240 — [hello-eureka-server] [ Thread-9] o.s.c.n.e.server.EurekaServerBootstrap : Initialized server context
2025-06-22T11:00:35.704+08:00 INFO 4240 — [hello-eureka-server] [ Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl : Got 1 instances from neighboring DS node
2025-06-22T11:00:35.705+08:00 INFO 4240 — [hello-eureka-server] [ Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl : Renew threshold is: 1
2025-06-22T11:00:35.705+08:00 INFO 4240 — [hello-eureka-server] [ Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl : Changing status to UP
2025-06-22T11:00:35.716+08:00 INFO 4240 — [hello-eureka-server] [ Thread-9] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2025-06-22T11:00:35.760+08:00 INFO 4240 — [hello-eureka-server] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8761 (http) with context path '/'
2025-06-22T11:00:35.763+08:00 INFO 4240 — [hello-eureka-server] [ main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8761
2025-06-22T11:00:35.837+08:00 INFO 4240 — [hello-eureka-server] [ main] c.e.h.e.s.HelloEurekaServerApplication : Started HelloEurekaServerApplication in 18.559 seconds (process running for 21.967)
2025-06-22T11:01:35.708+08:00 INFO 4240 — [hello-eureka-server] [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry : Running the evict task with compensationTime 0ms

注意日志中的警告:

  • OptionalValidatorFactoryBean 警告:缺少 Bean Validation 提供者(如 Hibernate Validator)。如果不需要参数验证功能,可以忽略此警告。
  • LoadBalancerCaffeineWarnLogger 警告:建议在生产环境使用 Caffeine 缓存替代默认缓存。对于开发测试,默认缓存足够。

七、验证 Eureka Server

  • 访问控制台: 打开浏览器,访问 Eureka Server 的管理控制台:http://localhost:8761/。
  • 查看状态:
    • Instances currently registered with Eureka 区域显示已注册的服务实例。初始状态下,因为配置了不注册,这里应该是空的。
    • 注意页面上的状态信息(如 UP)和系统状态。
  • Eureka Server 控制台截图

    图示:成功启动后的 Eureka Server 管理控制台首页。注意 ,instances 区域为空(尚未注册其他服务)。

    八、总结

    至此,一个基础的 Spring Cloud Eureka Server 注册中心已经成功搭建并运行在 http://localhost:8761。关键点在于:

  • 使用 spring-cloud-starter-netflix-eureka-server 依赖。
  • 在启动类上添加 @EnableEurekaServer 注解。
  • 正确配置 application.yml,特别是 eureka.client.register-with-eureka=false 和 eureka.client.fetch-registry=false 对于单机模式至关重要。
  • 默认端口 8761 可通过 server.port 修改。
  • 赞(0)
    未经允许不得转载:网硕互联帮助中心 » 服务发现:Eureka 服务器(Service Discovery: Eureka Server)
    分享到: 更多 (0)

    评论 抢沙发

    评论前必须登录!