9阅网

您现在的位置是:首页 > 知识 > 正文

知识

java - 停止sleuth为新线程创建新的跟踪ID的方法。

admin2022-11-07知识19

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.

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

Q: 究竟如何才能实现?



【回答】:

我觉得你可以继续主跨度像

https:/cloud.spring.iospring-cloud-sleuthreferencehtml#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.iospring-cloud-sleuthreferencehtml#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.iospring-cloud-sleuthreferencehtml#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.iospring-cloud-sleuthreferencehtml#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);

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

【回答】:

我并不精通这方面的知识,但我看到了一些帮助,来自于 https:/gitter.imspring-cloudspring-cloud-sleuth?at=5eb2b6f397338850a2ee2b3f。

一些建议贴在这里。

https:/github.comspring-cloudspring-cloud-sleuthissues1570#issuecomment-627181235。

你可以尝试先做订阅,然后再做你的可调用包装器。

【回答】:

为了解决这个问题,我需要使用 LazyTraceExecutor - org.springframework.cloud.sleuth.instrument.async.LazyTraceExecutor

实例--它的例子

LazyTraceExecutor lazyTraceExecutor;

@PostConstrucrt
void init() {
      LazyTraceExecutor lazyTraceExecutor =  new LazyTraceExecutor(this.beanFactory,
                                                        java.util.concurrent.Executors.newFixedThreadPool(10, threadFactory("Sched-A-%d"))
                                                                );
}

然后在我的RX方法中,产生新的线程。

Single<MyObject> methohThaCallAnotherRemoteService() {

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

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

            return response.getBody();

        })
        .subscribeOn(Schedulers.from(lazyTraceExecutor));  //  use it

现在我已经没有跨度的问题了。