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环境,对应的路由配置不会加载。
解决步骤
- 移除冲突依赖,删除pom.xml中的
spring-boot-starter-web依赖,同步排查是否存在其他间接引入WebMVC的依赖项:
<!-- 移除该依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- 补充路径截断过滤器,修改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
- 激活dev环境配置:启动服务时添加启动参数
--spring.profiles.active=dev,或在配置文件的公共区域添加spring.profiles.active=dev确保路由配置生效。 - 验证修改:重启网关后访问
localhost:9092/api/v0即可正常转发到localhost:8086/v0,拿到预期返回结果。
内容的提问来源于stack exchange,提问作者YK mar
相关产品推荐
相关产品推荐

