rpcx 调用 [通过 conetxt ]
最后更新于:2022-04-02 02:57:51
[TOC]
## rpcx 调用 [通过 conetxt ]
[rpcx_jaeger [master] ](https://github.com/idcpj/rpcx_jaeger)
核心代码,实现与 zipkin 还是稍有不同
```
func GenerateSpanWithContext(ctx context.Context, operationName string) (opentracing.Span, context.Context, error) {
md := ctx.Value(share.ReqMetaDataKey) // share.ReqMetaDataKey 固定值 "__req_metadata" 可自定义
var span opentracing.Span
tracer := opentracing.GlobalTracer()
if md != nil {
carrier := opentracing.TextMapCarrier(md.(map[string]string))
spanContext, err := tracer.Extract(opentracing.TextMap, carrier)
if err != nil && err != opentracing.ErrSpanContextNotFound {
log.Printf("metadata error %s\n", err)
return nil, nil, err
}
span = tracer.StartSpan(operationName, ext.RPCServerOption(spanContext))
} else {
span = opentracing.StartSpan(operationName)
}
metadata := opentracing.TextMapCarrier(make(map[string]string))
err := tracer.Inject(span.Context(), opentracing.TextMap, metadata)
if err != nil {
return nil, nil, err
}
//把metdata 携带的 traceid,spanid,parentSpanid 放入 context
ctx = context.WithValue(context.Background(), share.ReqMetaDataKey, (map[string]string)(metadata))
return span, ctx, nil
}
```
';