go-kit 微服務 服務鏈路追蹤 (jaeger 實現)(2)

hwholiday發表於2020-02-12

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)
        }
    }
}
  • 新增到登入 EndPoint 中
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
}
  • 新增到 server 方法中
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
}

執行

結語

  • 通過後臺介面我們可以看到請求資訊裡面新增上了我們對 service,endpoint 層的鏈路追蹤
  • jaeger 的用法還有很多,這裡只展示簡單的使用,更加高階的功能歡迎大家一起討論
  • 歡迎新增 QQ 一起討論

完整程式碼地址

聯絡 QQ: 3355168235

更多原創文章乾貨分享,請關注公眾號
  • go-kit 微服務 服務鏈路追蹤 (jaeger 實現)(2)
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章