go-kit 微服务 服务链路追踪(jaeger 实现)(2)

2020-01-13  本文已影响0人  hwholiday

go-kit 微服务 服务链路追踪(jaeger 实现)(2)

endpoint层

func NewTracerEndpointMiddleware(tracer opentracing.Tracer) endpoint.Middleware {
    return func(next endpoint.Endpoint) endpoint.Endpoint {
        return func(ctx context.Context, request interface{}) (response interface{}, err error) {
            span, ctxContext := opentracing.StartSpanFromContextWithTracer(ctx, tracer, "endpoint", opentracing.Tag{
                Key:   string(ext.Component),
                Value: "NewTracerEndpointMiddleware",
            })
            defer span.Finish()
            return next(ctxContext, request)
        }
    }
}
func NewEndPointServer(svc Service, limit *rate.Limiter,tracer opentracing.Tracer) EndPointServer {
    var loginEndPoint endpoint.Endpoint
    {
        loginEndPoint = MakeLoginEndPoint(svc)
        loginEndPoint = NewGolangRateAllowMiddleware(limit)(loginEndPoint)
        loginEndPoint = NewTracerEndpointMiddleware(tracer)(loginEndPoint)

    }
    return EndPointServer{LoginEndPoint: loginEndPoint}
}

service层修改

type tracerMiddlewareServer struct {
    next   Service
    tracer opentracing.Tracer
}
func NewTracerMiddlewareServer(tracer opentracing.Tracer) NewMiddlewareServer {
    return func(service Service) Service {
        return tracerMiddlewareServer{
            next:   service,
            tracer: tracer,
        }
    }
}
func (l tracerMiddlewareServer) Login(ctx context.Context, in *pb.Login) (out *pb.LoginAck, err error) {
    span, ctxContext := opentracing.StartSpanFromContextWithTracer(ctx, l.tracer, "service", opentracing.Tag{
        Key:   string(ext.Component),
        Value: "NewTracerServerMiddleware",
    })
    defer func() {
        span.Finish()
    }()
    out, err = l.next.Login(ctxContext, in)
    return
}
func NewService(log *zap.Logger, counter metrics.Counter, histogram metrics.Histogram, tracer opentracing.Tracer) Service {
    var server Service
    server = &baseServer{log}
    server = NewTracerMiddlewareServer(tracer)(server)
    server = NewMetricsMiddlewareServer(counter, histogram)(server)
    server = NewLogMiddlewareServer(log)(server)
    return server
}

运行

结语

完整代码地址

联系 QQ: 3355168235

上一篇 下一篇

猜你喜欢

热点阅读