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
}

运行

  • 运行 TestNewUserAgentClient 方法
  • 我们登录 http://127.0.0.1:16686/ jaeger后台查询信息

结语

  • 通过后台界面我们可以看到请求信息里面添加上了我们对service,endpoint层的链路追踪
  • jaeger的用法还有很多,这里只展示简单的使用,更加高级的功能欢迎大家一起讨论
  • 欢迎添加QQ一起讨论

完整代码地址

联系 QQ: 3355168235