gRPC 快速体验(5):gRPC-Gateway

简介

gRPC-Gateway是protoc的一个插件。它读取gRPC服务定义并生成反向代理服务器,该服务器将RESTful JSON API转换为gRPC。此服务器根据gRPC定义中的自定义选项生成。

grpc-gateway文档

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-261LV8LZ-1662048112939)(https://cdn.nlark.com/yuque/0/2022/svg/12487795/1662001502595-799f0c0c-c9d4-40f5-ac1d-5616856a30d5.svg#clientId=uef1d0fb0-3fe7-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=u46f7a2cf&margin=%5Bobject%20Object%5D&originHeight=760&originWidth=1120&originalType=url&ratio=1&rotation=0&showTitle=false&status=done&style=none&taskId=ufb7b917c-de12-448e-b5fb-6a5e8924871&title=)]

安装依赖

go get github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway

proto 文件

gateway/pb/gateway.proto 文件;其中 需要 import google/api/annotations.proto;可以将 github.com\grpc-ecosystem\grpc-gateway 下的 third_party\googleapis\google\api 文件拷贝到项目目录下;执行protoc命令

protoc -I=./gateway/pb/ -I=./third_party/ –go_out=./gateway/ –go-grpc_out=./gateway/ -grpc-gateway_out=./gateway/ ./gateway/pb/gateway.proto

syntax = "proto3";

package stream;

option go_package = "pb/;gateway";
import "google/api/annotations.proto";

message Request {
  string name = 1;
}

message Reply {
  string content = 1;
}

service GatewayDemo {
  rpc Gate(Request) returns (Reply) {
    option (google.api.http) = {
      get: "/v1/gate/{name}"
    };
  }
}

Server端

server端与正常gRPC服务没什么差别;

package main

import (
	"context"
	"fmt"
	"net"

	gateway "github.com/grpc-demo/gateway/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

type Gate struct {
	gateway.UnimplementedGatewayDemoServer
}

func (g Gate) Gate(ctx context.Context, req *gateway.Request) (*gateway.Reply, error) {
	return &gateway.Reply{
		Content: fmt.Sprintf("name:%s;", req.Name),
	}, nil
}

func main() {
	server := grpc.NewServer()
	gateway.RegisterGatewayDemoServer(server, &Gate{})
	reflection.Register(server)
	lis, _ := net.Listen("tcp", ":9000")
	_ = server.Serve(lis)
}

Http服务端

通过 gateway.RegisterGatewayDemoHandlerFromEndpoint 将http请求代理到给RPC服务;

package main

import (
	"context"
	"net/http"

	gateway "github.com/grpc-demo/gateway/pb"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const (
	// gRPC服务地址
	ServerAddr = "127.0.0.1:9000"

	ClientAddr = "127.0.0.1:8000"
)

func main() {
	ctx, cancelFunc := context.WithCancel(context.Background())
	defer cancelFunc()
	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
	err := gateway.RegisterGatewayDemoHandlerFromEndpoint(ctx, mux, ServerAddr, opts)
	if err != nil {
		panic(err)
	}
	err = http.ListenAndServe(ClientAddr, mux)
	if err != nil {
		panic(err)
	}
}

启动测试

go run server.go

访问 127.0.0.1:8000/v1/gate/grpc
同时也可以通过grpcurl 测试服务端

grpcurl -plaintext -d ‘{“name”:“grpc”}’ localhost:9000 stream.GatewayDemo/Gate

现在我启动SpringBoot应用程序就会报错,说9090端口已被占用,我就是怀疑我的配置没有生效,导致grpc默认绑定在了0.0.0.0:9090上面。目前的情况是这样的,我写了一个模块叫websocketpush,这个模块使用maven quickstart模板创建的,在依赖里面手动引入的spring-boot-starter、grpc-spring-boot-starter等依赖,然后我写了一个StompMsgHandlerServiceGrpcServer类,他实现了StompMsgHandleServiceGrpc.StompMsgHandleServiceImplBase接口,并且这个类上我使用了@GrpcService注解,接下来我在这个模块的resources目录下添加了application.yaml文件,在这个yaml文件中我配置了grpc.server.port为8850,address为0.0.0.0,再然后我原本项目中的另一个模块api-gateway在其pom文件中引入了websocketpush的依赖,这样的话api-gateway的SpringBoot程序在启动时就会去注册StompMsgHandlerServiceGrpcServer这个Bean,我的设想是api-gateway会读取到websocketpush模块中application.yaml文件中的grpc.server.port以及address,但是从错误信息上来看感觉是没有读取到,而且我能看到api-gateway自身的application.yaml文件中只配置了grpc.client,没有配置grpc.server的相关信息,如下所示: grpc: client: GLOBAL: negotiation-type: plaintext enable-keep-alive: true keep-alive-without-calls: true keep-alive-time: 30s keep-alive-timeout: 10s omada-manager: address: static://${grpc-host}:9090 omada-maintenance: address: static://${grpc-host}:9093 omada-monitor: address: static://${grpc-host}:9094 omada-log: address: static://${grpc-host}:9095 omada-identityaccess: address: static://${grpc-host}:9096 omada-client: address: static://${grpc-host}:9097 omada-insight: address: static://${grpc-host}:9099 这是为什么,该怎么解决
最新发布
10-30
<think>我们面临的问题:配置在 websocketpush 模块的 application.yaml 中的 grpc.server.port 和 address 没有被 api-gateway 模块正确读取,导致 gRPC 服务器仍然尝试绑定到默认的 9090 端口(已被占用)。 原因分析: 1. **模块间配置隔离**:Spring Boot 默认只会加载当前模块(api-gateway)的 `src/main/resources` 下的配置文件。虽然 websocketpush 模块有 application.yaml,但当它作为依赖被引入 api-gateway 时,其配置文件不会被自动加载。 2. **配置优先级**:即使 websocketpush 模块的配置被包含,Spring Boot 的配置文件加载有特定顺序和优先级,多个模块的配置不会自动合并。 解决方案: - **方案一(推荐)**:将 gRPC 服务器配置移到 api-gateway 模块的配置文件中。 在 api-gateway 的 application.yaml 中添加: ```yaml grpc: server: port: 8850 address: 0.0.0.0 ``` 这样确保 api-gateway 启动时能正确读取配置。 - **方案二**:如果希望保持配置在 websocketpush 模块,需确保该配置能被加载。但这不是标准做法,因为 websocketpush 的配置通常用于自身测试,作为库被引用时配置不会生效。 - **方案三(高级)**:使用 Spring Cloud Config 等配置中心统一管理配置,但会增加复杂度。 验证步骤: 1. 在 api-gateway 的配置中显式添加 gRPC 服务器配置。 2. 重启应用,观察日志中 gRPC 服务器是否绑定到 8850 端口。 §§相关问题§§1. 在 Spring Boot 多模块项目中,如何统一管理各模块的配置文件?2. gRPC 服务器的端口配置在哪些情况下会失效或覆盖?3. 如何通过日志验证 gRPC 服务的配置已生效?4. 除了端口冲突,还有哪些常见原因会导致 gRPC 服务启动失败?5. 如果同一个应用需要启动多个 gRPC 服务端口,应如何配置? </think>### 问题分析与解决方案 #### 原因分析 1. **配置未生效** `websocketpush` 模块的 `application.yaml` 未被 `api-gateway` 读取,因为: - Spring Boot **默认只加载主模块(api-gateway)的配置文件**,依赖模块的配置会被忽略。 - `api-gateway` 自身的配置中缺少 `grpc.server` 定义,导致 gRPC 服务启用时强制使用默认值(`0.0.0.0:9090`)。 2. **端口冲突** 默认的 9090 端口已被占用(可能是其他服务或之前的残留进程)。 --- #### 解决方案 ##### 步骤 1:显式配置 gRPC 服务器 在 **api-gateway 模块** 的 `application.yaml` 中**添加 gRPC 服务器配置**: ```yaml grpc: server: port: 8850 # 自定义端口 address: 0.0.0.0 client: # 保留原有 client 配置 GLOBAL: negotiation-type: plaintext enable-keep-alive: true # ...(其他 client 配置保持不变) ``` ##### 步骤 2:清理端口占用 ```bash # Linux/MacOS lsof -i :9090 # 查询占用进程 kill -9 <PID> # 终止进程 # Windows netstat -ano | findstr :9090 taskkill /PID <PID> /F ``` ##### 步骤 3:验证配置加载 在 `api-gateway` 启动类中添加测试代码: ```java @SpringBootApplication public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); // 打印 gRPC 配置 System.out.println("gRPC Server Port: " + Environment.getProperty("grpc.server.port", "未读取到配置")); } } ``` 预期输出:`gRPC Server Port: 8850` --- #### 关键逻辑说明 - ✅ **配置优先级**:Spring Boot 仅加载**主启动模块(api-gateway)** 的配置文件,依赖模块的配置需合并到主配置。 - ✅ **端口绑定**:gRPC 服务通过 `@GrpcService` 注册后,**必须**在启动模块配置 `grpc.server` 才会覆盖默认值。 - ️ **依赖传递**:`api-gateway` 引入 `websocketpush` 依赖时,仅传递 JAR 包(代码/注解),**不传递配置文件**。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Devin_S

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值