【问题标题】:Do we need to use different grpc connections for different streams for same client (specific to golang)?我们是否需要为同一个客户端(特定于 golang)的不同流使用不同的 grpc 连接?
【发布时间】:2021-06-21 14:11:14
【问题描述】:

我的项目(在 golang 中)有一个用例,我需要从单个 GRPC 客户端打开多个流到单个/多个 GRPC 服务器。

假设我的 proto 文件是 -

syntax = "proto3";
package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (stream HelloRequest) returns (stream HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}  

现在对于我的客户,我有 2 个选项 -

package main

import (
    "google.golang.org/grpc"
    "hello/grpc/helloworld"
)

func newConn() helloworld.GreeterClient {
    conn, err := grpc.Dial("localhost:9009", grpc.WithInsecure())
    if err != nil {
        panic(err)
    }
    return helloworld.NewGreeterClient(conn)
}

func clientWork(client helloworld.GreeterClient) {
    // client work
}

func main() {
    // option 1 - new connection objects for all streams
    for i:=0; i<1000; i++ {
        clientWork(newConn())
    }
    
    // option 2 - single connection object for all streams
    globalConn := newConn()
    for i:=0; i<1000; i++ {
        clientWork(globalConn)
    }
}

选项 1 为流使用新的 grpc.Conn

选项 2 对所有流使用单个全局 grpc.Conn

我的问题 - 他们是否有任何推荐的实现相同目标的方法(如果具体情况,我可以得到一些例子)

我查看了https://github.com/grpc/grpc-go/issues/2086#issuecomment-389947160,这表明要释放底层缓冲区/内存,我几乎没有选择,其中之一包括关闭 grpc.Conn,这让我开始思考哪个选项更适合我的情况。

谢谢

【问题讨论】:

  • fwiw,我一直在使用单个 grpc 连接来处理流和常规调用,但没有发现问题。
  • @BurakSerdar 遇到过类似github.com/grpc/grpc-go/issues/3728 的问题吗?我正在观察类似的问题
  • 到目前为止我还没有观察到这一点。

标签: go stream grpc grpc-go


【解决方案1】:

对于 gRPC,通常建议您对到同一服务器的所有流使用单个连接。主要的例外是对每个连接的并发流数量有限制的服务器。

【讨论】:

  • 后续问题,如果正在使用相同的连接,我们如何清除不再使用的流的缓冲区?如果我使用不同的连接对象,我可以简单地关闭它们,它会为流释放任何持有的内存。
  • 我认为您可以取消用于创建流的上下文,并且通过堆栈级联并清理流。请参阅 NewStream 的文档:pkg.go.dev/google.golang.org/grpc#ClientConn.NewStream
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 2016-10-08
  • 2020-10-25
  • 2021-02-06
  • 2012-06-12
  • 2015-10-14
相关资源
最近更新 更多