Java Brave Zipkin:每个不同的 http 请求的 TraceId 不变

Java Brave Zipkin: TraceId unchanged for each different http requests

关于 Java 和 Brave/Zipkin 的小追踪问题。

我有一个非常小的程序,使用 Java 11 和 Brave,版本如下:

        <dependency>
            <groupId>io.opentracing.brave</groupId>
            <artifactId>brave-opentracing</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.zipkin.reporter2</groupId>
            <artifactId>zipkin-sender-okhttp3</artifactId>
            <version>2.16.3</version>
        </dependency>

目标很简单,我是客户端,我有一个包含 N 个不同请求负载的列表,要向服务器发送 N 次 API。 (服务器上没有 API 我无法控制一次接受所有这些,问题不在于此)

由于我想利用跟踪技术,作为客户端,我想发送 N 个请求,因为 每个请求都是不同且唯一的,具有 N 个不同的 traceId。

为此,我尝试了:

private static Iterator<String> sendRequestPayloadToServerWithDifferentTraceId(Iterator<String> requestsPayload) {
        List<String> linkedList = new LinkedList<>();
        while (requestsPayload.hasNext()) {
            final OkHttpSender        sender   = OkHttpSender.newBuilder().endpoint("https://zipkin-server:9411/api/v2/spans").build();
            final AsyncReporter<Span> reporter = AsyncReporter.builder(sender).build();
            final Tracing             tracing  = Tracing.newBuilder().localServiceName("client").addSpanHandler(ZipkinSpanHandler.create(reporter)).build();
            tracing.tracer().startScopedSpan("parentSpan");
            final var span = tracing.tracer().currentSpan();
            span.tag("key", "firstBiz");

            tracing.tracer().startScopedSpanWithParent("childSpan", tracing.tracer().currentSpan().context());
            final var childSpan = tracing.tracer().currentSpan();
            childSpan.tag("key", "secondBiz");
            childSpan.finish();

            String requestPayload = requestsPayload.next();
            final WebClient webClient = WebClient.create().mutate().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE, HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap(true).protocol(HttpProtocol.H2))).build();
            LOGGER.info("sending the request! requestPayload={} TraceId={}, SpanId={}", requestPayload, span.context().traceIdString(), childSpan.context().traceIdString());
            final String response = webClient.post().uri("https://the-bsiness-server/api/someAPI").header("X-B3-TraceId", span.context().traceIdString()).header("X-B3-SpanId", childSpan.context().traceIdString()).body(BodyInserters.fromValue(requestPayload)).retrieve().bodyToMono(String.class).block();
            if (!"".equals(response)) {
                linkedList.add("OK");
            }
        }
        return linkedList.iterator();
    }

不幸的是,无论有多少请求,虽然我希望看到 N 个不同的 traceId,但我总是只看到一个相同的 traceId

我很难理解。 请问每个请求获得一个 unique/different 跟踪的正确方法是什么,请导致 N 个不同的请求?

谢谢

我对你的代码做了一点重构,注意 Reporter 上应用的刷新和关闭(提示:reporter 是异步的 ).还有创建 tracing 对象的逻辑,在 while 循环之前传输,我们使用 BraveTracer 作为跟踪器

  private static Iterator<String> sendRequestPayloadToServerWithDifferentTraceId(
      Iterator<String> requestsPayload) {

    List<String> linkedList = new LinkedList<>();

    final OkHttpSender sender = OkHttpSender.create("http://localhost:9411/api/v2/spans");

    AsyncReporter<Span> reporter = AsyncReporter.create(sender);
    Tracing tracing = Tracing
        .newBuilder()
        .localServiceName("client")
        .sampler(Sampler.create(1.0f))
        .addSpanHandler(ZipkinSpanHandler.create(reporter))
        .build();


    while (requestsPayload.hasNext()) {
      BraveTracer tracer = BraveTracer.create(tracing);
      BraveSpan parent = tracer
          .buildSpan("parent")
          .withTag("key", "firstBiz")
          .start();

      BraveSpan child = tracer
          .buildSpan("child")
          .withTag("key", "secondBiz")
          .asChildOf(parent)
          .start();

      child.finish();

      String requestPayload = requestsPayload.next();
      final WebClient webClient =
          WebClient.create()
              .mutate()
              .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE,
              HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).clientConnector(
              new ReactorClientHttpConnector(
                  HttpClient.create().wiretap(true).protocol(HttpProtocol.HTTP11))).build();
      final String response = webClient.post().uri("http://localhost:8081/api")
          .header("X-B3-TraceId", parent.unwrap().context().traceIdString())
          .header("X-B3-SpanId", child.unwrap().context().traceIdString())
          .body(BodyInserters.fromValue(requestPayload)).retrieve().bodyToMono(String.class)
          .block();
      if (!"".equals(response)) {
        linkedList.add("OK");
      }
      parent.finish(); // important
    }

    reporter.flush(); // important
    reporter.close(); // important
    return linkedList.iterator();
  }

添加以下依赖:

<dependency>
  <groupId>io.zipkin.brave</groupId>
  <artifactId>brave</artifactId>
  <version>5.13.7</version>
</dependency>

经过上述更改后,我能够为每个请求获取一个跟踪 ID,结果: