创建一个Brave
private Brave(Builder builder) { serverTracer = ServerTracer.builder() .randomGenerator(builder.random) .spanCollector(builder.spanCollector) .state(builder.state) .traceSampler(builder.sampler).build(); clientTracer = ClientTracer.builder() .randomGenerator(builder.random) .spanCollector(builder.spanCollector) .state(builder.state) .traceSampler(builder.sampler).build(); localTracer = LocalTracer.builder() .randomGenerator(builder.random) .spanCollector(builder.spanCollector) .spanAndEndpoint(SpanAndEndpoint.LocalSpanAndEndpoint.create(builder.state)) .traceSampler(builder.sampler).build(); serverRequestInterceptor = new ServerRequestInterceptor(serverTracer); serverResponseInterceptor = new ServerResponseInterceptor(serverTracer); clientRequestInterceptor = new ClientRequestInterceptor(clientTracer); clientResponseInterceptor = new ClientResponseInterceptor(clientTracer); serverSpanAnnotationSubmitter = AnnotationSubmitter.create(SpanAndEndpoint.ServerSpanAndEndpoint.create(builder.state)); serverSpanThreadBinder = new ServerSpanThreadBinder(builder.state); clientSpanThreadBinder = new ClientSpanThreadBinder(builder.state); }封装了*Tracer,*Interceptor,*Binder等
其中 serverTracer当服务作为服务端时处理span信息,clientTracer当服务作为客户端时处理span信息
Filter
BraveServletFilter是http模块提供的拦截器功能,传递serverRequestInterceptor,serverResponseInterceptor,spanNameProvider等参数
其中spanNameProvider表示如何处理span的名称,默认使用method名称,spring boot中申明的filter bean 默认拦截所有请求
首先来看requestInterceptor.handle方法,
public void handle(ServerRequestAdapter adapter) { serverTracer.clearCurrentSpan(); final TraceData traceData = adapter.getTraceData(); Boolean sample = traceData.getSample(); if (sample != null && Boolean.FALSE.equals(sample)) { serverTracer.setStateNoTracing(); LOGGER.fine("Received indication that we should NOT trace."); } else { if (traceData.getSpanId() != null) { LOGGER.fine("Received span information as part of request."); SpanId spanId = traceData.getSpanId(); serverTracer.setStateCurrentTrace(spanId.traceId, spanId.spanId, spanId.nullableParentId(), adapter.getSpanName()); } else { LOGGER.fine("Received no span state."); serverTracer.setStateUnknown(adapter.getSpanName()); } serverTracer.setServerReceived(); for(KeyValueAnnotation annotation : adapter.requestAnnotations()) { serverTracer.submitBinaryAnnotation(annotation.getKey(), annotation.getValue()); } } }其中serverTracer.clearCurrentSpan()清除当前线程上的span信息,调用ThreadLocalServerClientAndLocalSpanState中的
@Override public void setCurrentServerSpan(final ServerSpan span) { if (span == null) { currentServerSpan.remove(); } else { currentServerSpan.set(span); } }currentServerSpan为ThreadLocal对象
private final static ThreadLocal<ServerSpan> currentServerSpan = new ThreadLocal<ServerSpan>() {