【Spring Cloud Gateway】Nacos整合遇坑记:503 Service Unavailable
经过查阅 Spring Cloud 官方文档,我注意到从 Spring Cloud 2020版 本开始,Netflix Ribbon 被标记为进入维护模式,Spring 官方推荐使用Spring Cloud LoadBalancer 作为替代。最近在公司进行微服务架构升级,将原有的 Spring Cloud Hoxton 版本升级到最新的 2021.x 版本,同时使用 Nacos 作为服务注册中心
一、场景重现
最近在公司进行微服务架构升级,将原有的 Spring Cloud Hoxton 版本升级到最新的 2021.x 版本,同时使用 Nacos 作为服务注册中心和配置中心。在完成基础框架搭建后,我使用 Spring Cloud Gateway 作为API 网关,通过 Nacos 实现服务发现和动态路由。
一切看起来都很顺利,直到我开始测试网关路由功能时,遇到了令人困惑的 503 错误。具体场景如下:
- 我已经成功注册了两个微服务到N acos:user-service 和 order-service
- 在 Gateway 中配置了简单的路由规则:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/user/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/order/**
- 当通过网关访问/api/user/1时,却收到了503 Service Unavailable响应
查看日志发现如下关键错误信息:
Whitelabel Error Page
This application has no configured error view, so you are seeing this as a fallback.
Wed May 20 09:40:11 CST 2025
[fd8c3a90-7] There was an unexpected error (type=Service Unavailable, status=503).
二、问题排查
第一步:确认服务注册情况
首先我检查了 Nacos 控制台,确认 user-service 和 order-service 确实已经成功注册,且健康状态正常。这说明服务注册本身没有问题。
第二步:检查 Gateway 配置
路由配置看起来也没有问题,lb:// 前缀表示使用负载均衡,这是 Spring Cloud Gateway 的标准用法。
第三步:查阅文档和版本变化
经过查阅 Spring Cloud 官方文档,我注意到从 Spring Cloud 2020版 本开始,Netflix Ribbon 被标记为进入维护模式,Spring 官方推荐使用Spring Cloud LoadBalancer 作为替代。而在 Spring Cloud 2021 版本中,Ribbon被完全移除。
如果没有显式引入负载均衡器,Gateway 无法正确解析 lb:// 前缀
三、问题根源
问题的本质在于:
- Spring Cloud Gateway 依赖负载均衡器来解析 lb:// 服务名
- 从 Spring Cloud 2020 开始,Ribbon 被弃用
- 如果没有引入替代的负载均衡器,Gateway 无法找到可用的服务实例
四、解决方案
解决方法其实很简单:引入 Spring Cloud LoadBalancer 作为 Ribbon 的替代品。
在 Gateway 服务的 pom.xml 中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
添加依赖后,重启 Gateway 服务,再次测试路由功能,一切恢复正常。
更多推荐
所有评论(0)