猿问

在 grpc-go 的 stat/HandleRPC 中访问有关请求和响应负载的信息

我正在使用 stats/HandleRPC() 发出一些关于 RPC 持续时间的指标,当我收到 stats/End 数据时,我想用一些可以从传入和传出有效负载中提取的信息来标记这些指标。实现这一目标的最佳方法是什么?


func (h *myStatsHandler) HandleRPC(ctx context.Context, rpcStats stats.RPCStats) {

    switch stat := rpcStats.(type) {

    case *stats.End:

        durationMs := stat.EndTime.Sub(stat.BeginTime).Seconds() * 1000.0

        // Now before sending this value, I need to know, for example the value of a specific key in the request payload, or whether the response is nil or not 

    }

}


HUWWW
浏览 96回答 1
1回答

撒科打诨

在您的 实现中TagRPC,您可以创建一个结构并将指向它的指针添加到上下文中。然后通过对 的连续调用在其中添加信息HandleRPC。因此,如果您需要 Payload 中仅在*stats.InPayload调用中可用的内容,您可以将其拉出并将其存储在添加到上下文的结构中,然后在HandleRPC再次调用时访问它*stats.Endtype recorderCtxKey struct{}type recorder struct {    size   int64}func (sl *statsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {    return context.WithValue(ctx, rpcStatCtxKey{}, &recorder{})}func (h *statsHandler) HandleRPC(ctx context.Context, rpcStats stats.RPCStats) {    switch stat := rpcStats.(type) {    case *stats.InPayload:        r, _ := ctx.Value(recorderContextKey{}).(*Recorder)        r.size += stat.WireLength    case *stats.End:        durationMs := stat.EndTime.Sub(stat.BeginTime).Seconds() * 1000.0        r, _ := ctx.Value(recorderContextKey{}).(*Recorder)        # use r.size #    }}
随时随地看视频慕课网APP

相关分类

Go
我要回答