我们知道,Zipkin这个工具可以帮助我们收集分布式系统中各个系统之间的调用连关系,而且除了Servlet之外还能收集:MQ、线程池、WebSocket、Feign、Hystrix、RxJava、WebFlux等等组件之间的调用关系。本篇文章就来分析一下Zipkin是如何完成这些功能的
我们先以最常用的Servlet接受请求为例来分析
在spring-cloud-sleuth的spring.factories文件中注入的很多类中包含了一个类:TraceWebServletAutoConfiguration,一看就知道,这是为Servlet环境量身定制的一个自动装配类
在这个类中,创建了一个Filter,这个Filter就是拦截web请求,完成Servlet请求链路的收集的利器
@Bean
@ConditionalOnMissingBean
public TracingFilter tracingFilter(HttpTracing tracing) {
return (TracingFilter) TracingFilter.create(tracing);
}
我们直接来看这个拦截器都是做了一些什么东西吧
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = this.servlet.httpResponse(response);
TraceContext context = (TraceContext)request.getAttribute(TraceContext.class.getName());
if (context != null) {
Scope scope = this.currentTraceContext.maybeScope(context);
try {
chain.doFilter(request, response);
} finally {
scope.close();
}
} else {
Span span = this.handler.handleReceive(this.extractor, httpRequest);
request.setAttribute(SpanCustomizer.class.getName(), span.customizer());
request.setAttribute(TraceContext.class.getName(), span.context());
Throwable error = null;
Scope scope = this.currentTraceContext.newScope(span.context());
try {
chain.doFilter(httpRequest, httpResponse);
} catch (ServletException | RuntimeException | Error | IOException var19) {
error = var19;
throw var19;
} finally {
scope.close();
if (this.servlet.isAsync(httpRequest)) {
this.servlet.handleAsync(this.handler, httpRequest, span);
} else {
this.handler.handleSend(ADAPTER.adaptResponse(httpRequest, httpResponse), error, span);
}
}
}
}
Span的创建
第一步,尝试从request中获取TraceContext,TraceContext包含了本次请求的链路信息,假如这个请求是从上游系统过来的话,那么这里就会存在这个信息。
我们先重点看不存在上游系统时的分支,这个时候,第一步就应该去创建一个span。关于span和trace的概念上篇文章已经提到过了,这里就不再展开了。
public Span handleReceive(TraceContext.Extractor extractor, C carrier, Req request) {
Span span = nextSpan(extractor.extract(carrier), request);
span.kind(Span.Kind.SERVER);
return handleStart(request, span);
}
Span nex