java - 阻止侦探为新线程创建新跟踪 ID 的方法

标签 java spring-boot spring-cloud-sleuth

1.

线程1主线程

myClient.methohThaCallAnotherRemoteService();

2.

在我的 MyClient 类中,我们通过 restTeamplate 调用另一个服务

Single<MyObject> methohThaCallAnotherRemoteService() {

        return Single.fromCallable( () -> { ...

            final ResponseEntity<MyObject> response = restTemplate.postForEntity...

            return response.getBody();

        })
        .subscribeOn(Schedulers.io()); // to be run on separate threads / scheduler

3.

然后在ClientHttpRequestInterceptorImpl中定义为

   ClientHttpRequestInterceptorImpl implements  org.springframework.http.client.ClientHttpRequestInterceptor {
     ...
 public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) { ...

     log.info("HTTP_CLIENT_REQUEST" + logResponse));

问题是: 该 Sleuth 创建一个带有跨度的单独跟踪 id (trace-id-2)。日志如下所示:

来自主线程:

> INFO [my-app,trace-id-1, span-id-1] [nio-8080-exec-2] ...

来自 io 线程:

> INFO [my-app,trace-id-2, span-id-2,false] 117037 ---
> [readScheduler-2] d.p.i.w.ClientHttpRequestInterceptorImpl :
> {"logType":"HTTP_CLIENT_REQUEST"

我希望trace-id-2 为trace-id-1,这样我就可以跟踪从主线程到io 线程的请求。 (否则就追踪而言没有意义)。

我仍然希望我的 logger.info() 位于 ClientHttpRequestInterceptorImpl

问:具体如何实现?

最佳答案

我认为你可以像这样继续主要跨度

https://cloud.spring.io/spring-cloud-sleuth/reference/html/#continuing-spans-2

// method declaration
@ContinueSpan(log = "testMethod11")
void testMethod11(@SpanTag("testTag11") String param);

// method execution
this.testBean.testMethod11("test");
this.testBean.testMethod13();

https://cloud.spring.io/spring-cloud-sleuth/reference/html/#continuing-spans

// let's assume that we're in a thread Y and we've received
// the `initialSpan` from thread X
Span continuedSpan = this.tracer.toSpan(newSpan.context());
try {
    // ...
    // You can tag a span
    continuedSpan.tag("taxValue", taxValue);
    // ...
    // You can log an event on a span
    continuedSpan.annotate("taxCalculated");
}
finally {
    // Once done remember to flush the span. That means that
    // it will get reported but the span itself is not yet finished
    continuedSpan.flush();
}

https://cloud.spring.io/spring-cloud-sleuth/reference/html/#creating-spans-with-explicit-parent

// let's assume that we're in a thread Y and we've received
// the `initialSpan` from thread X. `initialSpan` will be the parent
// of the `newSpan`
Span newSpan = null;
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(initialSpan)) {
    newSpan = this.tracer.nextSpan().name("calculateCommission");
    // ...
    // You can tag a span
    newSpan.tag("commissionValue", commissionValue);
    // ...
    // You can log an event on a span
    newSpan.annotate("commissionCalculated");
}
finally {
    // Once done remember to finish the span. This will allow collecting
    // the span to send it to Zipkin. The tags and events set on the
    // newSpan will not be present on the parent
    if (newSpan != null) {
        newSpan.finish();
    }
}

https://cloud.spring.io/spring-cloud-sleuth/reference/html/#runnable-and-callable

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // do some work
    }

    @Override
    public String toString() {
        return "spanNameFromToStringMethod";
    }
};
// Manual `TraceRunnable` creation with explicit "calculateTax" Span name
Runnable traceRunnable = new TraceRunnable(this.tracing, spanNamer, runnable,
        "calculateTax");
// Wrapping `Runnable` with `Tracing`. That way the current span will be available
// in the thread of `Runnable`
Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
        .wrap(runnable);

以下示例展示了如何对 Callable 执行此操作:

Callable<String> callable = new Callable<String>() {
    @Override
    public String call() throws Exception {
        return someLogic();
    }

    @Override
    public String toString() {
        return "spanNameFromToStringMethod";
    }
};
// Manual `TraceCallable` creation with explicit "calculateTax" Span name
Callable<String> traceCallable = new TraceCallable<>(this.tracing, spanNamer,
        callable, "calculateTax");
// Wrapping `Callable` with `Tracing`. That way the current span will be available
// in the thread of `Callable`
Callable<String> traceCallableFromTracer = this.tracing.currentTraceContext()
        .wrap(callable);

这样,您就可以确保每次执行都会创建并关闭一个新的跨度。

关于java - 阻止侦探为新线程创建新跟踪 ID 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61659898/

相关文章:

java - Spring Boot Hibernate CRUD REST API 404错误

java - NoSuchBeanDefinitionException:当我使用自动配置时,没有名为 'elasticsearchTemplate'的bean可用

java - Spring Mail 中不允许域文字问题

java - 使用适用于 Java 的 Azure Monitor OpenTelemetry Exporter 客户端库自动导出 Spring Cloud Sleuth 跨度

java - Vaadin + CDI + 推送(大气)不起作用

java - try-catch 区域对性能有什么影响?

java - 添加 zipkin 和 sleuth 时无法启动应用程序

java - Spring Cloud Sleuth 错误发布跨越到 Zipkin

java - 将声音文件与 ImageView 或图像点击相匹配

java - 确保使用每个枚举值