You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud Gateway路由路径大小写问题排查求助

问题排查与解决方案

问题原因分析

出现大小写访问差异及404的核心原因有两点:

  1. Eureka服务名存储特性:Eureka默认会将注册的服务名转换为大写形式存储,你的serviceA在Eureka中实际注册为SERVICEA。
  2. Gateway路由配置问题:
    • 你开启了discovery.locator.enabled: true,Gateway会自动基于Eureka中的大写服务名生成路由(如/SERVICEA/**),且自动去除前缀转发到服务根路径,所以/SERVICEA能正常访问。
    • 你手动配置的serviceA路由,仅指定了Path=/serviceA/**,但没有添加前缀去除过滤器,导致请求被完整转发到serviceA的/serviceA路径,而你的ServiceAController只提供了根路径/的接口,因此返回404。

解决方案

方案1:修正手动路由配置(推荐)

修改API网关的application.yml,在手动路由中添加StripPrefix过滤器,去除请求路径中的/serviceA前缀,确保转发到serviceA的根路径:

spring:
  application:
    name: gatewayapi    
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
         
      routes:
      - id: serviceA
        uri: lb://serviceA
        predicates:
        - Path=/serviceA/**
        filters:
        - StripPrefix=1  # 去除路径中第一个前缀段(即/serviceA)

server:
  port: 8080

eureka:
  client:
    serviceUrl:
      defaultZone: http://service-registry:8761/eureka/

配置完成后,访问http://localhost:8080/serviceA会被转发到serviceA的/路径,正常返回"test"。

方案2:让自动生成路由支持小写服务名

如果你想保留自动生成的路由并支持小写访问,可以添加lowerCaseServiceId: true配置,让Gateway基于小写服务名生成路由:

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lowerCaseServiceId: true  # 开启小写服务名路由

此时/serviceA/**和/SERVICEA/**都能正常转发到serviceA服务。

补充说明

  • Spring Cloud Gateway的StripPrefix过滤器用于移除请求路径中指定数量的前缀段,这里StripPrefix=1表示移除第一个/serviceA部分。
  • Eureka的服务名大小写问题:虽然Eureka存储为大写,但Spring Cloud LoadBalancer在通过lb://serviceA寻址时,默认是大小写不敏感的,无需担心服务寻址失败。

内容的提问来源于stack exchange,提问作者emaSingolarità

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:27:43