我正在使用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/