我正在使用 gRPC 构建 API,并且在服务器端,我想在客户端断开连接时收到通知,识别它并基于此执行一些任务。
到目前为止,我能够使用grpc.StatsHandlermethod检测客户端断开连接HandleConn。我尝试使用上下文传递值,但无法从服务器端访问它们。
客户端:
conn, err := grpc.DialContext(
context.WithValue(context.Background(), "user_id", 1234),
address,
grpc.WithInsecure(),
)
Run Code Online (Sandbox Code Playgroud)
服务器端:
// 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) { …Run Code Online (Sandbox Code Playgroud)