Spring Cloud Gateway无法找到微服务返回404错误问题咨询
问题根因
返回404的核心原因是Spring Cloud Gateway默认会将完整请求路径原封不动转发到后端服务,你配置的路由规则仅做了路径匹配,未移除前缀/fx-service1、/fx-service2,导致后端服务接收到的路径包含额外前缀,无法匹配到对应接口。
解决方案
添加StripPrefix路径前缀移除过滤器
调整application.yml中的路由配置,新增filters配置移除第一层路径前缀:spring: application: name: API-GATEWAY cloud: gateway: routes: - id: FX-SERVICE1 uri: http://localhost:8005 predicates: - Path=/fx-service1/** filters: - StripPrefix=1 # 移除路径中第一段前缀,即/fx-service1 - id: FX-SERVICE2 uri: http://localhost:8006 predicates: - Path=/fx-service2/** filters: - StripPrefix=1 discovery: enabled: true server: port: 8081 eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ register-with-eureka: true fetch-registry: true instance: hostname: localhost配置完成后,请求
http://网关地址:8081/fx-service1/xxx会被转发为http://localhost:8005/xxx,匹配后端服务接口路径。清理无效冲突配置
当前配置中的spring.cloud.config.uri: http://localhost:8081指向网关自身端口,若你未使用Spring Cloud Config配置中心,直接删除该行配置即可,避免不必要的加载冲突。可选优化:基于Eureka实现动态路由(推荐)
你已经集成了Eureka客户端,无需写死后端服务地址端口,可直接通过服务名实现负载均衡和动态服务发现,修改路由uri格式为lb://<Eureka注册的服务名>即可,示例:- id: FX-SERVICE1 uri: lb://FX-SERVICE1 # 替换为你的服务在Eureka中注册的名称 predicates: - Path=/fx-service1/** filters: - StripPrefix=1验证排查手段
可开启actuator的gateway端点查看路由规则是否正确加载,在application.yml中添加如下配置:management: endpoints: web: exposure: include: gateway启动网关后访问
http://localhost:8081/actuator/gateway/routes即可查看所有已生效的路由规则。
内容的提问来源于stack exchange,提问作者Karla Calero
相关产品推荐
相关产品推荐

