Spring Boot API Gateway无法转发请求至Product Service问题求助
核心问题分析
报错提示网关在查找静态资源/api/product,说明API Gateway的路由规则未生效,请求没有被转发到Product Service,而是被当成静态资源请求处理。
可能的原因及解决步骤
1. Gateway项目错误引入了spring-boot-starter-web依赖
Spring Cloud Gateway基于WebFlux实现,若同时引入spring-boot-starter-web(Servlet栈),会导致Gateway的自动配置失效,项目退化为普通Web应用,路由规则完全不生效。
解决:
检查Gateway的pom.xml(或build.gradle),移除spring-boot-starter-web依赖,确保只保留以下核心依赖:
<!-- Spring Cloud Gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- Eureka Client 用于服务发现 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
2. 路由规则的Path匹配配置不完整
当前Gateway的Path predicate仅配置为Path=/api/product,属于精确匹配,仅能匹配http://localhost:8080/api/product这个路径(不含斜杠结尾、不含子路径),实际场景中需要覆盖更多请求情况。
优化配置:
修改Gateway的application.properties,调整路由规则为:
spring.cloud.gateway.routes[0].id=product-service spring.cloud.gateway.routes[0].uri=lb://product-service # 匹配/api/product及所有子路径 spring.cloud.gateway.routes[0].predicates[0]=Path=/api/product/**
3. 验证服务发现与实例可用性
确认以下两点:
- 在Eureka控制台(
http://localhost:8761)中,product-service的实例状态为UP - Gateway能正确拉取到
product-service的实例信息
验证方式:
在Gateway的application.properties中添加调试日志,查看路由匹配和服务发现情况:
logging.level.org.springframework.cloud.gateway=DEBUG logging.level.org.springframework.cloud.client.discovery=DEBUG
重启Gateway后发起请求,查看日志中是否有Route matched: product-service的记录,以及是否成功获取到product-service的实例地址。
4. 确认请求方法匹配
Product Controller提供了POST /api/product(创建产品)和GET /api/product(获取所有产品)接口,确保在Insomnia中发起的请求方法与接口一致。
测试验证
完成上述调整后,重启Gateway,再次发起http://localhost:8080/api/product的GET请求,应该能正常转发到Product Service并返回结果。
内容的提问来源于stack exchange,提问作者majd

