You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud Gateway路由不生效返回404故障排查求助

问题根因
  • 依赖冲突:Spring Cloud Gateway 基于Spring WebFlux实现,与spring-boot-starter-web(Spring WebMVC)依赖互斥,同时引入后WebMVC会覆盖网关的默认请求处理逻辑,导致路由规则完全不生效。
  • 路径转发规则缺失:当前仅配置了路径匹配规则,未配置前缀截断,请求/api/v0会完整转发到http://localhost:8086/api/v0,而非预期的http://localhost:8086/v0,若下游8086服务未暴露/api/**路径的接口,就会返回404。
  • 配置未激活:路由规则写在dev专属profile下,若服务启动时未激活dev环境,对应的路由配置不会加载。
解决步骤
  1. 移除冲突依赖,删除pom.xml中的spring-boot-starter-web依赖,同步排查是否存在其他间接引入WebMVC的依赖项:
<!-- 移除该依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 补充路径截断过滤器,修改dev环境网关配置,添加StripPrefix规则去掉第一层/api前缀:
# profil DEV
---
spring:
  profiles: dev
  cloud:
    gateway:
      routes:
        - id: pr-api-id
          uri: http://localhost:8086/
          predicates:
           - Path=/api/**
          filters:
           - StripPrefix=1 # 截断路径第一层前缀,即将/api/xxx转为/xxx
  1. 激活dev环境配置:启动服务时添加启动参数--spring.profiles.active=dev,或在配置文件的公共区域添加spring.profiles.active=dev确保路由配置生效。
  2. 验证修改:重启网关后访问localhost:9092/api/v0即可正常转发到localhost:8086/v0,拿到预期返回结果。

内容的提问来源于stack exchange,提问作者YK mar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:27:04