Spring Cloud Gateway本地地址路由失效,请求返回404问题求助
问题诊断与解决方案
你的404问题核心在于Spring Cloud Gateway的路由路径匹配规则和路径转发逻辑,以下是具体问题点和修复方案:
1. 路径匹配范围过窄
当前路由配置的path("/auth-service")和path("/concert-service")仅精确匹配不带斜杠的单一路径(如/auth-service),但你实际访问的是带斜杠的/auth-service/,且无法匹配后续子路径(如/auth-service/service-instances/xxx)。
2. 转发时未移除前缀
网关默认会把匹配到的完整路径转发到目标服务,比如当你访问/auth-service/时,网关会转发到http://10.0.2.15:8100/auth-service/,但Auth服务仅在根路径/提供接口,因此返回404。
修复后的路由配置
修改网关的customRouteLocator Bean,调整路径匹配规则并添加路径重写过滤器:
@EnableDiscoveryClient @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route(p -> p .path("/") .uri("http://google.com")) .route(p -> p .path("/auth-service/**") // 匹配所有以/auth-service开头的路径 .filters(f -> f.rewritePath("/auth-service/(?<segment>.*)", "/${segment}")) // 移除/auth-service前缀 .uri("http://10.0.2.15:8100")) .route(p -> p .path("/concert-service/**") // 匹配所有以/concert-service开头的路径 .filters(f -> f.rewritePath("/concert-service/(?<segment>.*)", "/${segment}")) // 移除/concert-service前缀 .uri("lb://concert-service")) .build(); } }
验证方法
- 重启网关服务后,访问
http://10.0.2.15:8762/auth-service/,应返回Auth服务的Welcome on Auth microservice api. - 访问
http://10.0.2.15:8762/concert-service/,应返回Concert服务的Welcome on Concert microservice api. - 测试子路径:访问
http://10.0.2.15:8762/auth-service/service-instances/auth-service,应返回Auth服务的实例信息
额外检查点
- 确认网关已引入Spring Cloud LoadBalancer依赖(使用
lb://协议必须依赖),如果使用Maven,需添加:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
- 确保Eureka Server中
auth-service和concert-service的实例状态为UP
内容的提问来源于stack exchange,提问作者Zapoux
相关产品推荐
相关产品推荐

