Eureka Server 3.x仅接收安全补丁,如何基于Spring Cloud LoadBalancer实现客户端缓存降级?

解读

国内大多数公司仍把 Eureka 作为“注册中心”的事实标准,但 Netflix 官方已宣布 Eureka Server 3.x 进入维护模式,只接受安全补丁,不再合并新特性。这意味着一旦服务端出现性能瓶颈或短暂宕机,客户端不能依赖服务端实时推送,必须自救。
Spring Cloud 2020 以后默认移除了 Ribbon,用 Spring Cloud LoadBalancer(SCLB) 作为官方替代。SCLB 的架构非常薄,只提供了 ServiceInstanceListSupplier 接口,允许我们在客户端本地缓存 + 降级,从而把 Eureka 仅当作“冷启动”的数据源,运行期不再强依赖。
面试时,考官想确认两点:

  1. 你是否知道 Eureka 3.x 的“维护模式”风险;
  2. 能否用 SCLB 的扩展点做出“缓存 + 降级”的高可用方案,而不是简单回答“换 Nacos”。

知识点

  1. Eureka 3.x 维护模式:只接受安全补丁,不保证新特性,社区版服务端性能天花板明显。
  2. Spring Cloud LoadBalancer 核心接口:
    • ServiceInstanceListSupplier:负责给 LoadBalancerClient 提供候选实例列表;
    • CachingServiceInstanceListSupplier:SCLB 自带的本地缓存装饰器,默认缓存 35 s,可自定义 TTL;
    • HealthCheckServiceInstanceListSupplier:主动探测实例存活,剔除不可用的节点。
  3. Spring Boot 条件装配:利用 @ConditionalOnProperty、@AutoConfigureBefore 把自定义实现插到官方默认实现之前,零侵入。
  4. 多级降级策略:
    ① 优先走本地缓存;
    ② 缓存失效且 Eureka 不可用时,走本地文件快照(JSON 格式,启动时兜底加载);
    ③ 仍无可用节点,返回空列表并触发业务侧熔断(Sentinel / Resilience4j),避免雪崩。
  5. 刷新机制:利用 Spring Event 监听 HeartbeatEvent 或 EnvironmentChangeEvent,在配置中心动态调整缓存 TTL,实现热更新。

答案

步骤一:引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!-- 如用 Eureka 作为数据源 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

步骤二:关闭 Ribbon 遗留代码,确保 SCLB 生效

spring:
  cloud:
    loadbalancer:
      ribbon:
        enabled: false   # 必须显式关闭,防止 Ribbon 残余影响

步骤三:编写自定义 Supplier,实现“缓存 + 文件快照”两级降级

public class FallbackServiceInstanceListSupplier implements ServiceInstanceListSupplier {

    private final ServiceInstanceListSupplier delegate;
    private final String serviceId;
    private final Path snapshotPath;

    public FallbackServiceInstanceListSupplier(ServiceInstanceListSupplier delegate, String serviceId) {
        this.delegate = delegate;
        this.serviceId = serviceId;
        this.snapshotPath = Paths.get("snapshots", serviceId + ".json");
    }

    @Override
    public String getServiceId() {
        return serviceId;
    }

    @Override
    public Flux<List<ServiceInstance>> get() {
        return delegate.get()
                       .onErrorResume(throwable -> {
                           log.warn("Eureka 不可用,尝试本地快照: {}", throwable.getMessage());
                           return Mono.just(readSnapshot());
                       })
                       .doOnNext(instances -> writeSnapshot(instances));
    }

    private List<ServiceInstance> readSnapshot() {
        if (Files.exists(snapshotPath)) {
            try {
                return new ObjectMapper().readValue(snapshotPath.toFile(), new TypeReference<List<DefaultServiceInstance>>() {});
            } catch (IOException e) {
                log.error("读取快照失败", e);
            }
        }
        return Collections.emptyList();   // 终极降级:空列表
    }

    private void writeSnapshot(List<ServiceInstance> instances) {
        try {
            Files.createDirectories(snapshotPath.getParent());
            new ObjectMapper().writeValue(snapshotPath.toFile(), instances);
        } catch (IOException e) {
            log.error("写入快照失败", e);
        }
    }
}

步骤四:用配置类把自定义 Supplier 插到 SCLB 责任链

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(value = "loadbalancer.fallback.enabled", matchIfMissing = true)
@AutoConfigureBefore(LoadBalancerAutoConfiguration.class)
public class FallbackLoadBalancerConfig {

    @Bean
    public ServiceInstanceListSupplier fallbackServiceInstanceListSupplier(
            ConfigurableApplicationContext context) {
        return ServiceInstanceListSupplier.builder()
                   .withBlockingDiscoveryClient()
                   .withCaching()                 // 第一层:35s 本地缓存
                   .withHealthCheck()             // 可选:主动探活
                   .additional((ctx, delegate) -> new FallbackServiceInstanceListSupplier(delegate, ctx.getServiceId()))
                   .build(context);
    }
}

步骤五:配合 Sentinel 做业务侧熔断

@SentinelResource(value = "getOrderService", fallback = "getOrderServiceFallback")
public List<OrderDTO> queryOrders() {
    List<ServiceInstance> instances = loadBalancerClient.choose("order-service");
    if (instances.isEmpty()) {
        throw new IllegalStateException("无可用节点");
    }
    // 正常调用
}
public List<OrderDTO> getOrderServiceFallback() {
    return Collections.emptyList();   // 返回本地缓存或默认值
}

通过以上五步,Eureka Server 即使完全挂掉,客户端仍能用本地缓存 + 文件快照继续路由,实现秒级自愈;同时利用 SCLB 的链式 API,代码零侵入、可热插拔,完全符合国内金融、电商等对高可用零容忍的落地场景。

拓展思考

  1. 快照文件的一致性:快照落在本地磁盘,遇到容器重启节点漂移,可把快照放到 Redis 或 OSS,实现“多 Pod 共享”。
  2. 缓存 TTL 动态化:把 spring.cloud.loadbalancer.cache.ttl 键值放到 Nacos / Apollo,利用 @ConfigurationProperties 刷新,运行时调整缓存有效期,压测时降 TTL 保证实时性,平时升 TTL 降低 Eureka 压力。
  3. 与 Kubernetes 结合:在 K8s 环境,可用 Spring Cloud Kubernetes 的 EndpointSlice 作为兜底数据源,实现“Eureka 挂掉后自动切换到 K8s 原生服务发现”,形成双注册中心高可用架构。
  4. 灰度场景:在自定义 Supplier 里增加 元数据版本过滤,配合 Spring Cloud Gateway + 灰度标记头,实现“注册中心宕机时仍按缓存版本路由”,保证灰度流量不乱。
  5. 未来演进:Eureka 维护模式不可逆,长期方案应规划 双注册中心平滑迁移(Eureka → Nacos 或 Consul),但客户端缓存降级机制依旧可以复用,保护现有投资,实现“换注册中心业务无感”。