在与grpc.ClientStreams进行交互时,您是否需要调用Recv直到收到io.EOF?

huangapple go评论88阅读模式
英文:

Are you required to call Recv until you get io.EOF when interacting with grpc.ClientStreams?

问题

假设我定义了以下的 gRPC 服务:

service Library {
  rpc Search(SearchBookRequest) returns (stream SearchBookResponse) {} 
}

message SearchBookRequest {
  string term = 1;
  int32 max_results = 2;
}

message SearchBookResponse {
  int32 book_id = 1;
}

它会将搜索结果以流的形式返回,最多返回指定数量的结果。当通过 gRPC 的 Go API 与服务进行交互时,我是否可以像下面这样做?

for i:=0; i<maxResults; i++ {
  search_result, err := stream.Recv()
  if err == io.EOF {
    // 注意:如果返回了 `maxResults`,则永远不会执行到这里。
    break
  }
  if err != nil {
    log.Fatalf("search error: %v", err)
  }
  fmt.Printf("Book-ID: %d\n", search_result.BookId)
}

还是说我必须不断调用 Recv 直到收到 io.EOF,以确保 gRPC 正确清理其所有资源?

英文:

Suppose I define the following gRPC service:

service Library {
  rpc Search(SearchBookRequest) returns (stream SearchBookResponse) {} 
}

message SearchBookRequest {
  string term = 1;
  int32 max_results = 2;
}

message SearchBookResponse {
  int32 book_id = 1;
}

It streams search results back up to a specified maximum. When interacting with the service via gRPC's Go API, am I allowed to do something like this?

for i:=0; i&lt;maxResults; i++ {
  search_result, err := stream.Recv()
  if err == io.EOF {
    // Note: If `maxResults` are returned this will never be reached.
    break
  }
  if err != nil {
    log.Fatalf(&quot;search error: %v&quot;, err)
  }
  fmt.Printf(&quot;Book-ID: %d\n&quot;, search_result.BookId)
}

Or am I required to keep calling Recv until I get io.EOF to ensure that gRPC properly cleans up all its resources?

答案1

得分: 1

你的代码是正确的。

你可以在出现错误时退出,不需要等待 EOF。


编辑:上面的答案不完整。

调用者应该一直接收,直到出现错误,否则可能会出现泄漏。还有其他避免泄漏的方法,比如取消上下文。详细信息请参阅 https://pkg.go.dev/google.golang.org/grpc#ClientConn.NewStream

英文:

Your code is correct.

You can exit on errors. You don't need to wait for an EOF.


Edit: the answer above is incomplete.

The caller should keep receiving until an error, otherwise there could be leaks. There are other ways to avoid leaks, like canceling the context. See https://pkg.go.dev/google.golang.org/grpc#ClientConn.NewStream for details.

huangapple
  • 本文由 发表于 2017年3月21日 06:45:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/42915337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定