在与grpc.ClientStreams交互时,你是否需要调用Recv,直到获得io.EOF? [英] Are you required to call Recv until you get io.EOF when interacting with grpc.ClientStreams?
问题描述
假设我定义了下面的gRPC服务:
pre $ service $ library $ {
rpc Search(SearchBookRequest)returns(stream SearchBookResponse){}
}
message SearchBookRequest {
string term = 1;
int32 max_results = 2;
}
消息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 \\\
,search_result.BookId)
}
或者我需要继续调用 Recv
,直到我得到 io.EOF
,以确保gRPC正确清理其所有资源?
您的代码是正确的。
对错误。您无需等待EOF。
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<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("search error: %v", err)
}
fmt.Printf("Book-ID: %d\n", 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?
Your code is correct.
You can exit on errors. You don't need to wait for an EOF.
这篇关于在与grpc.ClientStreams交互时,你是否需要调用Recv,直到获得io.EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!