go - 如何处理服务器上客户端的断开连接

标签 go grpc

我正在使用gRPC构建监视系统。为此,我需要知道gRPC客户端是否崩溃并因此与gRPC服务器断开连接。
这就是我创建服务器的方式。

var kaep = keepalive.EnforcementPolicy{
    MinTime:             5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection
    PermitWithoutStream: true,            // Allow pings even when there are no active streams
}

var kasp = keepalive.ServerParameters{
    MaxConnectionIdle:     15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY
    MaxConnectionAgeGrace: 5 * time.Second,  // Allow 5 seconds for pending RPCs to complete before forcibly closing connections
    Time:                  5 * time.Second,  // Ping the client if it is idle for 5 seconds to ensure the connection is still active
    Timeout:               1 * time.Second,  // Wait 1 second for the ping ack before assuming the connection is dead
}

    s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp))
    pb.RegisterHeartbeatGRPCServer(s, bt)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
我发现,保持 Activity 的概念可能对检测断开连接的客户端很有用。
https://github.com/grpc/grpc-go/blob/master/Documentation/keepalive.md
但是,我不确定如何处理断开连接。
如何处理这种断开?更确切地说,我想在客户端断开连接时调用ClientDisconnected(clientId)函数。那可能吗?

最佳答案

您可能要为此使用统计处理程序。特别是,您在寻找ConnEnd操作:
https://godoc.org/google.golang.org/grpc/stats#ConnEnd
https://godoc.org/google.golang.org/grpc/stats#Handler(您正在寻找TagConn和HandleConn)
https://godoc.org/google.golang.org/grpc#StatsHandler

关于go - 如何处理服务器上客户端的断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654489/

相关文章:

testing - 处理模糊错误时如何保持良好的 Go 包测试覆盖率?

go - 如何编写惯用的构造函数

grpc - Quarkus 阻止 grpc vert.x 事件循环错误

java - 在 gRPC 中使用直接类以避免数据复制

java - Grpc.Core.RpcException 方法未使用 C# 客户端和 Java 服务器实现

protocol-buffers - 如果删除 protobuf 上的字段会发生什么?

go - Go 中的 .a 文件是什么?

json - 如何从 stdin 中解析一个无限的 json 数组?

go - 涉及 CSV 文件的 io.Reader 和换行符问题

golang-grpc 服务 - 从另一个文件导入类型