【发布时间】:2019-09-20 19:23:59
【问题描述】:
我正在使用 gRPC 构建一个 API,在服务器端,我希望在客户端断开连接时收到通知,识别它并基于此执行一些任务。
到目前为止,我能够使用grpc.StatsHandler 方法HandleConn 检测到客户端断开连接。我尝试使用上下文传递值,但无法从服务器端访问它们。
客户端:
conn, err := grpc.DialContext(
context.WithValue(context.Background(), "user_id", 1234),
address,
grpc.WithInsecure(),
)
服务器端:
// Build stats handler
type serverStats struct {}
func (h *serverStats) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
return ctx
}
func (h *serverStats) HandleRPC(ctx context.Context, s stats.RPCStats) {}
func (h *serverStats) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context {
return context.TODO()
}
func (h *serverStats) HandleConn(ctx context.Context, s stats.ConnStats) {
fmt.Println(ctx.Value("user_id")) // Returns nil, can't access the value
switch s.(type) {
case *stats.ConnEnd:
fmt.Println("client disconnected")
break
}
}
// Build server
s := grpc.NewServer(grpc.StatsHandler(&serverStats{}))
我想在服务器端访问从客户端传递的值。正确的做法是什么,或者有没有其他方法可以识别已断开连接的客户端?
【问题讨论】:
-
I tried passing values using context我不确定具体细节,但如果您使用 GRPC 元数据可能会出现这种情况:(github.com/grpc/grpc-go/blob/master/Documentation/…),但我不确定 GRPC 方法调用的顺序以及何时/如何/何处在 nGRPC 协议中发送元数据(即它是否总是在HandleConn中可用?你的用例是什么?通过使操作幂等(或可能的其他方法)来处理断开连接可能有替代方法。