无法将gRPC与Spring Cloud Gateway集成的问题排查
Spring Cloud Gateway集成gRPC遇到服务不可用问题
问题场景
我正尝试将gRPC集成到Spring Cloud Gateway中,通过网关URL结合proto文件请求,将流量转发至gRPC服务。部署配置后,访问网关URL grpc://<api-gateway-host>:8080/grpc-api 时出现“service unavailable error”,但直接访问gRPC服务地址 grpc://grpc-test:50053 一切正常。
当前配置
网关application.yml配置
server: port: 8080 http2: enabled: true spring: application: name: API Gateway main: banner-mode: "off" web-environment: false web-application-type: reactive allow-bean-definition-overriding: true allow-circular-references: true cloud: gateway: filter: remove-hop-by-hop: headers: - connection - keep-alive - transfer-encoding - proxy-authenticate - proxy-authorization - x-application-context - upgrade httpclient: wiretrap: true ssl: use-insecure-trust-manager: true httpserver: wiretrap: true routes: - id: grpc-test uri: ${service_grpc_url:grpc://grpc-test:50053} predicates: - Path= /grpc-api/** filters: - RewritePath=/grpc-api(?<segment>/?.*), $\{segment}
已添加的依赖
implementation (group: 'org.springframework.cloud', name: 'spring-cloud-starter-netflix-eureka-client') implementation (group: 'org.springframework.boot', name: 'spring-boot-starter-security') implementation (group: 'org.springframework.boot', name: 'spring-boot-starter-web') implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation' implementation group: 'org.springframework.cloud', name: 'spring-cloud-openfeign-core'
环境版本
- Spring Boot: 3.2.3
- Spring Cloud: 2023.0.0
问题排查与解决方案
添加gRPC核心依赖
Spring Cloud Gateway本身不自带gRPC转发能力,必须添加专门的扩展依赖。在build.gradle中加入:implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-gateway' implementation group: 'io.grpc', name: 'grpc-netty-shaded', version: '1.61.0' // 版本需与你的gRPC服务匹配 implementation group: 'org.springframework.cloud', name: 'spring-cloud-gateway-grpc'其中
spring-cloud-gateway-grpc是处理gRPC流量的核心模块,没有它网关无法识别grpc://类型的URI。移除冲突依赖
当前依赖中的spring-boot-starter-web是Servlet栈依赖,而Spring Cloud Gateway基于Reactive Web栈,两者会冲突,导致网关无法正确处理gRPC依赖的HTTP/2流量。必须移除该行:// 移除以下依赖 // implementation (group: 'org.springframework.boot', name: 'spring-boot-starter-web')调整路由配置
- 修正
RewritePath的YAML语法,无需转义$,可以改为:- RewritePath=/grpc-api/(?<segment>.*), /$\{segment} - 检查启动日志,确认
service_grpc_url环境变量是否正确注入,路由使用的实际URI是否为grpc://grpc-test:50053。
- 修正
验证HTTP/2配置
虽然已开启server.http2.enabled=true,但需确认网关的HTTP服务器确实支持HTTP/2。gRPC完全依赖HTTP/2传输,若网关HTTP/2未正常启用,会直接导致服务不可用。可以通过日志或HTTP/2检测工具验证。
内容的提问来源于stack exchange,提问作者ShivaniK
相关产品推荐
相关产品推荐

