Spring Cloud Gateway配置正确但路由不生效问题求助
Spring Cloud Gateway 路由失效问题排查

现有部署配置
Eureka注册中心
- 已引入服务注册中心相关依赖,添加对应配置注解
server: port: 8761 eureka: client: register-with-eureka: false fetch-registry: false
业务服务(HEALTH-CARD)
- 主启动类已添加
@EnableEurekaClient注解
server: port: 9009 spring: application: name: HEALTH-CARD eureka: instance: hostname: localhost client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://${eureka.instance.hostname}:8761/eureka/
API网关服务
- 主启动类已添加
@EnableEurekaClient注解 - 已尝试YML配置路由:
server: port: 8080 spring: application: name: API-GATEWAY cloud: gateway: discovery: locator: enabled: true routes: - id: health-card uri: http://localhost:9009/health-card predicates: - Path=/** eureka: instance: hostname: localhost client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://${eureka.instance.hostname}:8761/eureka/
- 已尝试Java编码配置路由:
package com.apigateway.config; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Configuration; @Configuration public class SpringApiGatewayConfig { public RouteLocator configRoute(RouteLocatorBuilder builder) { return builder.routes() .route("healthCard", r->r.path("/health-card/**").uri("localhost:9009/")).build(); } }
已尝试该类问题所有常规解决方案,路由功能仍未正常工作。
问题修复方案
按优先级逐一排查修复:
- Java路由配置不生效问题
配置类中定义RouteLocator的方法缺少@Bean注解,Spring无法识别加载该路由规则;同时uri配置缺少HTTP协议头,属于非法地址。修正后代码:@Configuration public class SpringApiGatewayConfig { @Bean // 必须添加该注解,路由才会生效 public RouteLocator configRoute(RouteLocatorBuilder builder) { return builder.routes() .route("healthCard", r->r.path("/health-card/**") // 按需添加路径剥离过滤器,若业务接口无/health-card前缀则开启 // .filters(f -> f.stripPrefix(1)) .uri("http://localhost:9009")) // 补全http协议头,移除多余路径后缀 .build(); } } - YML路由配置错误问题
- 硬编码uri多拼接了
/health-card路径:当前断言规则为Path=/**,网关会把请求全路径直接拼接到uri后,比如请求/test会被转发到http://localhost:9009/health-card/test,和业务实际接口路径不匹配就会返回404 - 既然已经接入Eureka,不需要硬编码服务地址,直接用服务发现路由即可,修正后配置:
spring: cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true # 开启服务名小写匹配,避免大写服务名访问异常 routes: - id: health-card uri: lb://HEALTH-CARD # 走Eureka服务发现,自动负载均衡,无需写死IP端口 predicates: - Path=/health-card/** filters: - StripPrefix=1 # 转发前去掉路径第一层/health-card前缀,适配业务接口路径 - 硬编码uri多拼接了
- 依赖冲突问题
检查网关服务pom文件,绝对不能引入spring-boot-starter-web依赖。Spring Cloud Gateway基于WebFlux响应式框架实现,和Tomcat starter存在核心依赖冲突,会直接导致路由转发功能失效,若已引入直接排除即可。 - 连通性校验
三个服务全部启动后,先直接访问业务服务本地接口http://localhost:9009/[接口路径]确认业务服务本身运行正常,再通过网关地址http://localhost:8080/health-card/[接口路径]访问验证。不要用/**作为全局路由断言,会和网关内置端点、静态资源路径冲突。
内容的提问来源于stack exchange,提问作者Prakash
相关产品推荐
相关产品推荐

