为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
HUWWW 2022-12-26 10:20:55
我正在使用 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     }}
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

在您的 实现中TagRPC,您可以创建一个结构并将指向它的指针添加到上下文中。然后通过对 的连续调用在其中添加信息HandleRPC。因此,如果您需要 Payload 中仅在*stats.InPayload调用中可用的内容,您可以将其拉出并将其存储在添加到上下文的结构中,然后在HandleRPC再次调用时访问它*stats.End


type 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 #

    }

}


查看完整回答
反对 回复 2022-12-26
  • 1 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号