【发布时间】:2020-06-30 09:37:33
【问题描述】:
我正在使用 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)
}
我发现 keep-alive 的概念可能会派上用场来检测断开连接的客户端。 https://github.com/grpc/grpc-go/blob/master/Documentation/keepalive.md
但是,我不确定如何处理断开连接。
如何处理这种断开连接?更准确地说,我想在客户端断开连接时调用函数ClientDisconnected(clientId)。这可能吗?
【问题讨论】: