英文:
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<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?
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论