查看 grpc-go 中 stat/HandleRPC 的请求和响应负载信息
时间:2024-03-03
浏览:490
作者:佚名
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《查看 grpc-go 中 stat/HandleRPC 的请求和响应负载信息》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
问题内容
当我收到 stats/end 数据时,我正在使用 stats/handlerpc() 发出一些有关 rpc 持续时间的指标,并且我想用一些可以从传入和传出有效负载中提取的信息来标记指标。实现这一目标的最佳方法是什么?
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
}
}
正确答案
在 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 #
}
}今天关于《查看 grpc-go 中 stat/HandleRPC 的请求和响应负载信息》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
