
spring cloud gateway 通过 eureka 动态路由时返回 404,通常源于 yaml 配置格式错误;将配置从 application.yml 迁移至 application.properties 可规避缩进与语法解析问题,快速恢复路由功能。
spring cloud gateway 通过 eureka 动态路由时返回 404,通常源于 yaml 配置格式错误;将配置从 application.yml 迁移至 application.properties 可规避缩进与语法解析问题,快速恢复路由功能。
在基于 Spring Cloud Gateway + Eureka 的微服务架构中,网关应能自动发现并代理注册在 Eureka 上的服务(如 USER-SERVICE),但实践中常出现「直连微服务端口正常,经网关访问却返回 404 Not Found」的问题。尽管服务已成功注册到 Eureka(可通过 http://localhost:8761 确认 USER-SERVICE 在线),且网关配置看似正确,根本原因往往隐藏在 YAML 文件的格式敏感性中。
你提供的 application.yml 片段存在典型格式问题:
server:
port: 9191 # ❌ 缺少缩进,应为 2 空格对齐
spring:
application:
name: API-GATEWAY
cloud:
gateway:
routes:
- id: USER-SERVICE
uri: lb://USER-SERVICE/ # ✅ 正确使用 lb:// 协议
predicates:
- Path=/user/** # ✅ 路径匹配正确
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: true
fetch-registry: true
instance:
hostname: localhost
⚠️ 注意:YAML 对缩进极其严格。server.port 若未与 spring 同级缩进(即顶格或错位),Spring Boot 将无法正确绑定配置,导致 spring.cloud.gateway.routes 未被加载——此时网关实际未注册任何路由,所有请求均因无匹配规则而落入默认 404。
✅ 推荐解决方案:改用 application.properties(更鲁棒、免缩进困扰):
# application.properties server.port=9191 spring.application.name=API-GATEWAY spring.cloud.gateway.routes[0].id=USER-SERVICE spring.cloud.gateway.routes[0].uri=lb://USER-SERVICE/ spring.cloud.gateway.routes[0].predicates[0]=Path=/user/** eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ eureka.client.register-with-eureka=true eureka.client.fetch-registry=true eureka.instance.hostname=localhost
该写法明确声明路由索引([0]),避免嵌套结构解析歧义,且完全规避 YAML 缩进风险。配合以下验证步骤可确保生效:
启动 Eureka Server(端口 8761);
启动
USER-SERVICE(确保其spring.application.name=user-service,且已注册);-
启动 Gateway,观察控制台日志是否包含:
RouteDefinition matched: USER-SERVICE Loaded RoutePredicateFactory [Path]
-
发起测试请求:
curl http://localhost:9191/user/list # 应转发至 USER-SERVICE 的 /user/list
? 额外建议:
- 若坚持使用 YAML,请用 YAML Lint 工具校验格式;
- 在
application.yml中启用调试日志:logging.level.org.springframework.cloud.gateway=DEBUG,便于排查路由加载状态; - 确保
USER-SERVICE的实际接口路径与网关Path断言一致(例如/user/**不会匹配/api/user/**,需调整 predicate 或添加filters重写路径)。
通过配置格式标准化,即可让 Spring Cloud Gateway 稳定发挥服务发现与智能路由的核心能力。











