登录
首页 >  Golang >  Go问答

检查 gRPC 一元调用连接状态的服务器

来源:stackoverflow

时间:2024-02-06 22:39:20 481浏览 收藏

你在学习Golang相关的知识吗?本文《检查 gRPC 一元调用连接状态的服务器》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有一个一元 grpc 调用,在我的 go grpc 服务器上处理可能需要长达几分钟的时间(涉及移动应用程序上的人工代理)。我想知道是否有办法在发送响应之前检查客户端的连接是否已终止。

我找到了带有 context status.done 通道的 serverstreaming 案例的解决方案,但它不适用于我的 unary rpc。

下面是应进行控制的函数的签名:

func (*Server) EndpointName(ctx context.Context, in *pb.EndpointRequest) (*pb.EndpointResponse, error) {

正确答案


根据问题中显示的函数定义,端点函数传递了 context (ctx context.context)。如果连接断开,上下文将被取消。

例如,我可以修改 helloworld example,以便它模拟长时间运行的作业:

func (s *server) sayhello(ctx context.context, in *pb.hellorequest) (*pb.helloreply, error) {
    select {
    case <-ctx.done():
        fmt.println("context is done:", ctx.err())
        return nil, status.error(codes.canceled, "does not matter as nothing will ever get this anyway...")
    case <-time.after(time.minute):
        // this simulates a long-running process. in reality the process itself should be checking the context
    }
    return &pb.helloreply{}, nil
}

为了测试这一点,我更改了 greeter_client 来调用该函数,然后在等待响应时调用 panic() ;服务器输出:

2022/08/08 08:16:57 server listening at [::]:50051
Context is done: context canceled

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>