Spring Cloud Netflix 注册中心 Eureka 从入门到精通 - server:

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 317 次阅读

1. Eureka 概述与核心概念

1.1 什么是服务注册与发现

在微服务架构中,服务注册与发现是核心组件之一。随着服务数量的增加,服务之间的调用关系变得复杂,传统的硬编码服务地址的方式已无法满足需求。

服务注册与发现解决了以下问题:

动态管理服务实例(上线、下线)

实现服务调用的负载均衡

提高系统的弹性和可扩展性

简化服务配置管理

1.2 Eureka 简介

Eureka 是 Netflix 开源的服务发现框架,Spring Cloud 将其集成到 Spring Cloud Netflix 项目中,为 Spring Boot 应用提供了自配置的 Eureka 服务发现支持。

Eureka 的特点:

基于 REST 的服务注册与发现

支持高可用集群部署

提供自我保护机制

与 Spring Cloud 生态无缝集成

1.3 Eureka 架构核心组件

Eureka Server(注册中心)

服务注册表,存储所有可用的服务实例信息

提供 REST API 用于服务注册、续约和下线

维护客户端与服务实例的心跳机制

Eureka Client(服务客户端)

将自身服务注册到 Eureka Server

从 Eureka Server 获取服务注册表

定期发送心跳到 Eureka Server

在关闭时从 Eureka Server 注销

Eureka 集群

多个 Eureka Server 实例相互注册,形成高可用集群

服务注册表在集群间同步

2. Eureka Server 详细配置与部署

2.1 基础环境准备

系统要求:

JDK 8 或更高版本

Maven 3.2+ 或 Gradle 4+

Spring Boot 2.3+

Spring Cloud Hoxton.SR8+

2.2 创建 Eureka Server 项目

pom.xml 配置:

xml

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

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.3.12.RELEASE

com.example

eureka-server

1.0.0

1.8

Hoxton.SR12

org.springframework.cloud

spring-cloud-starter-netflix-eureka-server

org.springframework.boot

spring-boot-starter-security

org.springframework.boot

spring-boot-starter-actuator

org.springframework.cloud

spring-cloud-dependencies

${spring-cloud.version}

pom

import

2.3 Eureka Server 主类配置

java

package com.example.eurekaserver;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@SpringBootApplication

@EnableEurekaServer

public class EurekaServerApplication {

public static void main(String[] args) {

SpringApplication.run(EurekaServerApplication.class, args);

}

/**

* Spring Security 配置,为了 Eureka 控制台可访问

*/

@EnableWebSecurity

static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(HttpSecurity http) throws Exception {

// 忽略 Eureka 相关端点的 CSRF 保护

http.csrf().ignoringAntMatchers("/eureka/**");

super.configure(http);

}

}

}

2.4 详细配置文件解析

application.yml 单机配置:

yaml

server:

port: 8761

spring:

application:

name: eureka-server

security:

user:

name: admin

password: admin123

eureka:

instance:

hostname: localhost

# 实例ID配置

instance-id: ${spring.cloud.client.ip-address}:${server.port}

# 续约更新时间间隔(单位:秒)

lease-renewal-interval-in-seconds: 30

# 续约到期时间(单位:秒)

lease-expiration-duration-in-seconds: 90

# 优先使用IP地址进行注册

prefer-ip-address: true

# IP地址

ip-address: ${spring.cloud.client.ip-address}

client:

# 是否从其他Eureka Server获取注册信息(单机false)

fetch-registry: false

# 是否将自己注册到其他Eureka Server(单机false)

register-with-eureka: false

# Eureka Server服务端地址

service-url:

defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/

server:

# 启用自我保护模式

enable-self-preservation: true

# 清理无效节点间隔(单位:毫秒,默认60*1000)

eviction-interval-timer-in-ms: 60000

# 响应缓存更新间隔(单位:毫秒)

response-cache-update-interval-ms: 30000

# 是否使用只读响应缓存

use-read-only-response-cache: true

# 管理端点配置

management:

endpoints:

web:

exposure:

include: "*"

endpoint:

health:

show-details: always

2.5 Eureka Server 集群配置

集群节点1 application-peer1.yml:

yaml

server:

port: 8761

spring:

application:

name: eureka-server

profiles: peer1

security:

user:

name: admin

password: admin123

eureka:

instance:

hostname: peer1

prefer-ip-address: true

instance-id: ${eureka.instance.hostname}:${server.port}

client:

fetch-registry: true

register-with-eureka: true

service-url:

defaultZone: http://admin:admin123@peer2:8762/eureka/,http://admin:admin123@peer3:8763/eureka/

集群节点2 application-peer2.yml:

yaml

server:

port: 8762

spring:

application:

name: eureka-server

profiles: peer2

security:

user:

name: admin

password: admin123

eureka:

instance:

hostname: peer2

prefer-ip-address: true

instance-id: ${eureka.instance.hostname}:${server.port}

client:

fetch-registry: true

register-with-eureka: true

service-url:

defaultZone: http://admin:admin123@peer1:8761/eureka/,http://admin:admin123@peer3:8763/eureka/

集群节点3 application-peer3.yml:

yaml

server:

port: 8763

spring:

application:

name: eureka-server

profiles: peer3

security:

user:

name: admin

password: admin123

eureka:

instance:

hostname: peer3

prefer-ip-address: true

instance-id: ${eureka.instance.hostname}:${server.port}

client:

fetch-registry: true

register-with-eureka: true

service-url:

defaultZone: http://admin:admin123@peer1:8761/eureka/,http://admin:admin123@peer2:8762/eureka/

主机配置(/etc/hosts 或 C:\Windows\System32\drivers\etc\hosts):

text

127.0.0.1 peer1 peer2 peer3

2.6 高可用部署方案

方案一:同机房集群部署

所有节点部署在同一机房

网络延迟低,数据同步快

风险:机房级故障

方案二:跨机房部署

节点分布在多个机房

提高容灾能力

需要考虑网络延迟和数据一致性

方案三:多区域部署

不同区域部署独立集群

通过区域感知实现流量路由

实现全局高可用

3. Eureka Client 详细配置与使用

3.1 服务提供者配置

pom.xml 依赖:

xml

org.springframework.cloud

spring-cloud-starter-netflix-eureka-client

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-actuator

服务提供者主类:

java

package com.example.serviceprovider;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import java.util.Map;

@SpringBootApplication

@EnableDiscoveryClient

public class ServiceProviderApplication {

public static void main(String[] args) {

SpringApplication.run(ServiceProviderApplication.class, args);

}

}

/**

* 服务提供者控制器

*/

@RestController

@RequestMapping("/api/v1")

class ProviderController {

@GetMapping("/user/{id}")

public MapgetUser(@PathVariable String id) {

Mapuser = new HashMap<>();

user.put("id", id);

user.put("name", "用户-" + id);

user.put("timestamp", System.currentTimeMillis());

user.put("service", "service-provider");

return user;

}

@PostMapping("/user")

public MapcreateUser(@RequestBody Mapuser) {

user.put("id", System.currentTimeMillis());

user.put("createdTime", System.currentTimeMillis());

return user;

}

/**

* 健康检查端点

*/

@GetMapping("/health")

public Maphealth() {

Maphealth = new HashMap<>();

health.put("status", "UP");

health.put("timestamp", System.currentTimeMillis());

return health;

}

}

服务提供者配置 application.yml:

yaml

server:

port: 8081

spring:

application:

name: service-provider

profiles:

active: dev

# Eureka Client 配置

eureka:

client:

# Eureka Server 服务地址

service-url:

defaultZone: http://admin:admin123@localhost:8761/eureka/,http://admin:admin123@localhost:8762/eureka/,http://admin:admin123@localhost:8763/eureka/

# 获取服务注册列表间隔(单位:秒,默认30)

registry-fetch-interval-seconds: 30

# 是否从Eureka Server获取注册信息

fetch-registry: true

# 是否注册到Eureka Server

register-with-eureka: true

instance:

# 实例ID格式

instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}

# 实例显示名称

appname: ${spring.application.name}

# 续约更新时间间隔(单位:秒)

lease-renewal-interval-in-seconds: 30

# 续约到期时间(单位:秒)

lease-expiration-duration-in-seconds: 90

# 优先使用IP地址

prefer-ip-address: true

# IP地址

ip-address: ${spring.cloud.client.ip-address}

# 元数据配置

metadata-map:

cluster: default

version: 1.0.0

region: north

# 状态页URL路径

status-page-url-path: /actuator/info

# 健康检查URL路径

health-check-url-path: /actuator/health

# 主页URL路径

home-page-url-path: /

# 端点配置

management:

endpoints:

web:

exposure:

include: health,info,metrics

endpoint:

health:

show-details: always

# 自定义配置

service:

config:

max-connections: 100

timeout: 5000

3.2 服务消费者配置

服务消费者主类:

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.bind.annotation.*;

import org.springframework.web.client.RestTemplate;

import java.util.Map;

@SpringBootApplication

@EnableDiscoveryClient

public class ServiceConsumerApplication {

public static void main(String[] args) {

SpringApplication.run(ServiceConsumerApplication.class, args);

}

/**

* 启用负载均衡的RestTemplate

*/

@Bean

@LoadBalanced

public RestTemplate restTemplate() {

return new RestTemplate();

}

}

/**

* 服务消费者控制器

*/

@RestController

@RequestMapping("/api/v1")

class ConsumerController {

private final RestTemplate restTemplate;

public ConsumerController(RestTemplate restTemplate) {

this.restTemplate = restTemplate;

}

@GetMapping("/user/{id}")

public MapgetUser(@PathVariable String id) {

// 使用服务名进行调用,而不是具体的IP和端口

String serviceUrl = "http://service-provider/api/v1/user/" + id;

return restTemplate.getForObject(serviceUrl, Map.class);

}

@PostMapping("/user")

public MapcreateUser(@RequestBody Mapuser) {

String serviceUrl = "http://service-provider/api/v1/user";

return restTemplate.postForObject(serviceUrl, user, Map.class);

}

/**

* 健康检查端点

*/

@GetMapping("/health")

public Maphealth() {

Maphealth = new HashMap<>();

health.put("status", "UP");

health.put("timestamp", System.currentTimeMillis());

health.put("service", "service-consumer");

return health;

}

}

服务消费者配置 application.yml:

yaml

server: 拼多多帮助力入口

port: 8082

spring:

application:

name: service-consumer

# Eureka Client 配置

eureka:

client:

service-url:

defaultZone: http://admin:admin123@localhost:8761/eureka/,http://admin:admin123@localhost:8762/eureka/,http://admin:admin123@localhost:8763/eureka/

registry-fetch-interval-seconds: 30

fetch-registry: true

register-with-eureka: true

instance:

instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}

prefer-ip-address: true

ip-address: ${spring.cloud.client.ip-address}

lease-renewal-interval-in-seconds: 30

lease-expiration-duration-in-seconds: 90

# 负载均衡配置

ribbon:

# 连接超时时间(单位:毫秒)

ConnectTimeout: 2000

# 读取超时时间(单位:毫秒)

ReadTimeout: 5000

# 对当前实例的重试次数

MaxAutoRetries: 1

# 切换实例的重试次数

MaxAutoRetriesNextServer: 2

# 对所有操作请求都进行重试

OkToRetryOnAllOperations: true

# 日志配置

logging:

level:

com.netflix.loadbalancer: DEBUG

org.springframework.cloud.netflix.ribbon: DEBUG

3.3 高级客户端配置

自定义负载均衡策略:

java

package com.example.serviceconsumer.config;

import com.netflix.loadbalancer.IRule;

import com.netflix.loadbalancer.RandomRule;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class RibbonConfiguration {

/**

* 自定义负载均衡规则

* 默认是轮询,这里改为随机

*/

@Bean

public IRule ribbonRule() {

return new RandomRule();

}

}

/**

* 针对特定服务的负载均衡配置

*/

@Configuration

@RibbonClient(name = "service-provider", configuration = RibbonConfiguration.class)

public class ServiceProviderRibbonConfig {

// 特定服务的负载均衡配置

}

自定义实例过滤器:

java

package com.example.serviceconsumer.filter;

import com.netflix.appinfo.InstanceInfo;

import com.netflix.loadbalancer.Server;

import com.netflix.loadbalancer.ZoneAffinityServerListFilter;

import org.springframework.stereotype.Component;

import java.util.List;

import java.util.stream.Collectors;

/**

* 自定义服务实例过滤器

*/

@Component

public class CustomServerListFilter extends ZoneAffinityServerListFilter{

@Override

public ListgetFilteredListOfServers(Listservers) {

// 先调用父类的区域亲和性过滤

ListfilteredServers = super.getFilteredListOfServers(servers);

// 自定义过滤逻辑:只选择版本为1.0.0的服务实例

return filteredServers.stream()

.filter(server ->{

InstanceInfo instanceInfo = (InstanceInfo) server.getMetaInfo();

String version = instanceInfo.getMetadata().get("version");

return "1.0.0".equals(version);

})

.collect(Collectors.toList());

}

}

4. Eureka 核心原理深度解析

4.1 服务注册机制

注册流程:

客户端启动时,向 Eureka Server 发送注册请求

Eureka Server 将实例信息存储到注册表

客户端定期发送心跳维持注册状态

客户端关闭时发送注销请求

核心源码分析:

java

// EurekaClientAutoConfiguration 自动配置类

@Bean

@ConditionalOnMissingBean(value = {EurekaClientConfig.class})

public EurekaClientConfigBean eurekaClientConfigBean(ConfigurableEnvironment env) {

EurekaClientConfigBean client = new EurekaClientConfigBean();

// 客户端配置初始化

return client;

}

// DiscoveryClient 注册核心类

public class DiscoveryClient implements EurekaClient {

// 注册方法

void register() {

// 构造注册信息

InstanceInfo reinfo = this.instanceInfo.copy();

// 发送注册请求

httpResponse = eurekaTransport.registrationClient.register(reinfo);

}

// 心跳方法

boolean renew() {

// 发送心跳请求

httpResponse = eurekaTransport.registrationClient.sendHeartBeat();

}

}

4.2 服务发现机制

发现流程:

客户端启动时从 Eureka Server 获取全量注册表

客户端定期增量更新注册表

客户端缓存注册表信息,即使 Eureka Server 宕机也能继续服务

Ribbon 基于注册表实现客户端负载均衡

注册表缓存机制:

java

public class DiscoveryClient implements EurekaClient {

// 获取注册表

public Applications getApplications() {

return localRegionApps.get();

}

// 更新注册表缓存

private void updateDelta(Applications delta) {

// 合并增量更新到本地缓存

}

// 定时获取增量更新

class CacheRefreshThread implements Runnable {

public void run() {

// 定期从服务器获取增量更新

getAndUpdateDelta(applications);

}

}

}

4.3 自我保护机制

自我保护原理:

当短时间内大量服务实例下线时,Eureka 会进入自我保护模式

在自我保护模式下,不会立即删除过期的服务实例

防止因网络分区导致的服务实例被误删

相关配置:

yaml

eureka:

server:

# 启用自我保护

enable-self-preservation: true

# 自我保护阈值因子(默认0.85)

renewal-percent-threshold: 0.85

# 期望每分钟最小续约数

expected-client-renewal-interval-seconds: 30

# 清理任务执行间隔

eviction-interval-timer-in-ms: 60000

自我保护判断逻辑:

java

public class PeerAwareInstanceRegistryImpl extends AbstractInstanceRegistry {

protected boolean isLeaseExpirationEnabled() {

// 如果开启了自我保护,且当前续约比例低于阈值,则禁用租约过期

if (!selfPreservationModeEnabled) {

return true;

}

return numberOfRenewsPerMinThreshold > 0

&& getNumOfRenewsInLastMin() > numberOfRenewsPerMinThreshold;

}

}

4.4 多级缓存机制

Eureka Server 缓存层级:

一级缓存:只读缓存

java

public class ResponseCacheImpl implements ResponseCache {

// 只读缓存

private final ConcurrentMapreadOnlyCacheMap =

new ConcurrentHashMap();

// 读写缓存

private final LoadingCachereadWriteCacheMap;

// 注册表缓存

private final AtomicReferenceapplications =

new AtomicReference();

}

缓存更新流程:

客户端注册、续约、下线时,清空读写缓存

定时任务每30秒将读写缓存同步到只读缓存

客户端默认从只读缓存获取服务列表

客户端可以设置强制从读写缓存读取最新数据

5. Eureka 高级特性与最佳实践

5.1 元数据管理与使用

自定义元数据配置:

yaml

eureka:

instance:

metadata-map:

# 系统元数据

cluster: production

version: 2.1.0

region: north-china

zone: zone-1

# 业务元数据

weight: 100

environment: prod

features: feature1,feature2

# 自定义标签

tags: important,core-service

基于元数据的服务路由:

java

package com.example.serviceconsumer.route;

import com.netflix.appinfo.InstanceInfo;

import com.netflix.loadbalancer.Server;

import com.netflix.loadbalancer.ZoneAffinityServerListFilter;

import org.springframework.cloud.netflix.ribbon.SpringClientFactory;

import org.springframework.stereotype.Component;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;

/**

* 基于元数据的路由过滤器

*/

@Component

public class MetadataAwareFilter extends ZoneAffinityServerListFilter{

private final SpringClientFactory clientFactory;

public MetadataAwareFilter(SpringClientFactory clientFactory) {

this.clientFactory = clientFactory;

}

@Override

public ListgetFilteredListOfServers(Listservers) {

// 获取当前请求的元数据标签(可从ThreadLocal或请求头获取)

String requiredVersion = getCurrentRequestVersion();

String requiredZone = getCurrentRequestZone();

return servers.stream()

.filter(server ->{

InstanceInfo instanceInfo = (InstanceInfo) server.getMetaInfo();

Mapmetadata = instanceInfo.getMetadata();

// 版本匹配

boolean versionMatch = metadata.getOrDefault("version", "").equals(requiredVersion);

// 区域匹配

boolean zoneMatch = metadata.getOrDefault("zone", "").equals(requiredZone);

return versionMatch && zoneMatch;

})

.collect(Collectors.toList());

}

private String getCurrentRequestVersion() {

// 从请求上下文获取版本信息

// 实际项目中可以从请求头、ThreadLocal等获取

return "2.1.0";

}

private String getCurrentRequestZone() {

// 从请求上下文获取区域信息

return "zone-1";

}

}

5.2 健康检查与状态管理

自定义健康检查器:

java

package com.example.serviceprovider.health;

import org.springframework.boot.actuate.health.Health;

import org.springframework.boot.actuate.health.HealthIndicator;

import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

/**

* 自定义健康检查指示器

*/

@Component

public class CustomHealthIndicator implements HealthIndicator {

private final AtomicBoolean isHealthy = new AtomicBoolean(true);

@Override

public Health health() {

if (isHealthy.get()) {

return Health.up()

.withDetail("service", "service-provider")

.withDetail("timestamp", System.currentTimeMillis())

.withDetail("custom-check", "OK")

.build();

} else {

return Health.down()

.withDetail("service", "service-provider")

.withDetail("timestamp", System.currentTimeMillis())

.withDetail("custom-check", "FAILED")

.build();

}

}

/**

* 动态设置健康状态(可用于灰度发布等场景)

*/

public void setHealthy(boolean healthy) {

isHealthy.set(healthy);

}

}

基于健康状态的服务下线:

java

package com.example.serviceprovider.lifecycle;

import com.netflix.appinfo.ApplicationInfoManager;

import org.springframework.context.SmartLifecycle;

import org.springframework.stereotype.Component;

/**

* 服务生命周期管理

*/

@Component

public class ServiceLifecycleManager implements SmartLifecycle {

private final ApplicationInfoManager applicationInfoManager;

private boolean isRunning = false;

public ServiceLifecycleManager(ApplicationInfoManager applicationInfoManager) {

this.applicationInfoManager = applicationInfoManager;

}

@Override

public void start() {

isRunning = true;

// 服务启动时设置为OUT_OF_SERVICE状态,等待健康检查通过

applicationInfoManager.setInstanceStatus(InstanceStatus.OUT_OF_SERVICE);

}

@Override

public void stop() {

isRunning = false;

// 优雅关闭:先设置为DOWN状态,等待流量切走后再关闭

applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN);

}

/**

* 服务准备就绪,可以接收流量

*/

public void setServiceReady() {

applicationInfoManager.setInstanceStatus(InstanceStatus.UP);

}

/**

* 服务维护中,不接收新流量

*/

public void setServiceMaintenance() {

applicationInfoManager.setInstanceStatus(InstanceStatus.OUT_OF_SERVICE);

}

}

5.3 监控与指标收集

Eureka Server 监控端点:

java

package com.example.eurekaserver.monitor;

import com.netflix.eureka.registry.PeerAwareInstanceRegistry;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;

import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

import org.springframework.stereotype.Component;

import java.util.HashMap;

import java.util.Map;

/**

* 自定义Eureka监控端点

*/

@Component

@Endpoint(id = "eureka-stats")

public class EurekaStatsEndpoint {

private final PeerAwareInstanceRegistry registry;

public EurekaStatsEndpoint(PeerAwareInstanceRegistry registry) {

this.registry = registry;

}

@ReadOperation

public MapeurekaStats() {

Mapstats = new HashMap<>();

// 注册实例统计

stats.put("totalInstances", registry.getSortedApplications().size());

stats.put("renewalThreshold", registry.getNumOfRenewsPerMinThreshold());

stats.put("renewalLastMin", registry.getNumOfRenewsInLastMin());

stats.put("selfPreservation", registry.isLeaseExpirationEnabled());

// 应用统计

MapappStats = new HashMap<>();

registry.getSortedApplications().forEach(application ->{

appStats.put(application.getName(), application.getInstances().size());

});

stats.put("applicationStats", appStats);

return stats;

}

}

Prometheus 指标收集:

yaml

management:

endpoints:

web:

exposure:

include: health,info,metrics,prometheus,eureka-stats

metrics:

export:

prometheus:

enabled: true

distribution:

percentiles-histogram:

http.server.requests: true

5.4 安全配置

Eureka Server 安全配置:

java

package com.example.eurekaserver.security;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication()

.passwordEncoder(new BCryptPasswordEncoder())

.withUser("admin")

.password("$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBOsl7iKTV6UiC")

.roles("ADMIN")

.and()

.withUser("client")

.password("$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBOsl7iKTV6UiC")

.roles("CLIENT");

}

@Override

protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable()

.authorizeRequests()

.antMatchers("/eureka/css/**", "/eureka/js/**", "/eureka/fonts/**").permitAll()

.antMatchers("/eureka/**").hasAnyRole("ADMIN", "CLIENT")

.anyRequest().authenticated()

.and()

.httpBasic();

}

}

客户端安全配置:

yaml

eureka:

client:

service-url:

defaultZone: http://admin:admin123@peer1:8761/eureka/,http://admin:admin123@peer2:8762/eureka/

6. Eureka 故障排查与性能优化

6.1 常见问题排查

服务注册失败排查:

java

// 启用调试日志

logging:

level:

com.netflix.discovery: DEBUG

org.springframework.cloud.netflix: DEBUG

// 注册失败常见原因:

// 1. 网络连通性问题

// 2. 认证失败

// 3. 实例配置错误

// 4. Eureka Server 自我保护模式

服务发现失败排查:

java

// 检查客户端缓存

@Autowired

private DiscoveryClient discoveryClient;

@GetMapping("/services")

public ListgetServices() {

return discoveryClient.getServices();

}

@GetMapping("/instances/{serviceId}")

public ListgetInstances(@PathVariable String serviceId) {

return discoveryClient.getInstances(serviceId);

}

6.2 性能优化配置

Eureka Server 优化:

yaml

eureka:

server:

# 响应缓存更新时间(毫秒)

response-cache-update-interval-ms: 30000

# 禁用只读缓存(提高一致性,降低性能)

use-read-only-response-cache: false

# 注册表同步批处理大小

batch-replication-size: 100

# 最大并发复制线程数

max-peer-replication-threads: 20

# 最大并发复制任务数

maxThreadsForPeerReplication: 20

# 同步副本超时时间

peer-node-read-timeout-ms: 20000

instance:

# 租约续约间隔

lease-renewal-interval-in-seconds: 15

# 租约过期时间

lease-expiration-duration-in-seconds: 45

Eureka Client 优化:

yaml

eureka:

client:

# 注册表获取间隔

registry-fetch-interval-seconds: 30

# 初始注册表获取超时时间

initial-instance-info-replication-interval-seconds: 40

# 实例信息复制间隔

instance-info-replication-interval-seconds: 30

instance:

# 元数据刷新间隔

metadata-map-refresh-interval-ms: 30000

# HTTP客户端配置

ribbon:

ConnectTimeout: 2000

ReadTimeout: 5000

MaxTotalConnections: 500

MaxConnectionsPerHost: 100

# 启用重试

OkToRetryOnAllOperations: true

MaxAutoRetries: 1

MaxAutoRetriesNextServer: 2

6.3 大规模集群优化

分区部署策略:

yaml

# 区域1配置

eureka:

client:

region: north-china

availability-zones:

north-china: zone-1,zone-2

service-url:

zone-1: http://eureka-zone1-1:8761/eureka/,http://eureka-zone1-2:8761/eureka/

zone-2: http://eureka-zone2-1:8761/eureka/,http://eureka-zone2-2:8761/eureka/

instance:

metadata-map:

zone: ${eureka.instance.availability-zone}

分级缓存策略:

java

// 自定义多级缓存实现

public class MultiLevelResponseCache implements ResponseCache {

private final ResponseCache localCache; // 本地缓存

private final ResponseCache distributedCache; // 分布式缓存

@Override

public String get(Key key) {

// 先查本地缓存

String value = localCache.get(key);

if (value == null) {

// 本地缓存未命中,查询分布式缓存

value = distributedCache.get(key);

if (value != null) {

// 回填本地缓存

localCache.put(key, value);

}

}

return value;

}

}

7. Eureka 与其他组件的集成

7.1 与 Spring Cloud Gateway 集成

网关配置:

yaml

spring:

cloud:

gateway:

discovery:

locator:

enabled: true

lower-case-service-id: true

routes:

- id: service-provider

uri: lb://service-provider

predicates:

- Path=/api/v1/user/**

filters:

- name: RequestRateLimiter

args:

redis-rate-limiter.replenishRate: 10

redis-rate-limiter.burstCapacity: 20

- name: Retry

args:

retries: 3

methods: GET,POST

7.2 与 Spring Cloud Config 集成

配置中心集成:

yaml

# bootstrap.yml

spring:

cloud:

config:

discovery:

enabled: true

service-id: config-server

fail-fast: true

retry:

initial-interval: 1000

max-interval: 2000

max-attempts: 6

eureka:

client:

config:

service-url:

defaultZone: http://admin:admin123@eureka1:8761/eureka/

7.3 与 Spring Cloud Sleuth 集成

分布式链路追踪:

yaml

spring:

sleuth:

sampler:

probability: 1.0

web:

client:

enabled: true

zipkin:

base-url: http://zipkin-server:9411/

sender:

type: web

discovery-client-enabled: true

# 在日志中显示跟踪ID

logging:

pattern:

level: "%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]"

8. Eureka 2.x 与替代方案

8.1 Eureka 2.x 架构变化

主要改进:

引入推送机制替代拉取模式

改进集群同步协议

增强监控和可观测性

优化大规模集群性能

8.2 主流替代方案比较

Consul:

基于 Raft 协议,强一致性

支持服务发现、健康检查、KV存储

内置服务网格功能

Nacos:

支持AP和CP模式切换

集成配置管理功能

中文文档完善,社区活跃

Zookeeper:

强一致性保证

适合配置管理和领导者选举

服务发现功能相对较弱

总结

Eureka 作为 Spring Cloud Netflix 生态的核心组件,提供了成熟稳定的服务注册与发现解决方案。通过本文的详细讲解,您应该已经掌握了:

Eureka 的核心原理和架构设计

单机和集群环境的部署配置

客户端的高级配置和使用技巧

性能优化和故障排查方法

与其他微服务组件的集成方案

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧