在使用Sleuth做链路跟踪时,默认情况下异步线程会断链,需要进行代码调整支持。
使用@Async实现异步线程
- @EnableAsync
- @SpringBootApplication
- public class LizzApplication {
- public static void main(String[] args) {
- SpringApplication.run(LizzApplication.class, args);
- }
- }
- @Slf4j
- @Service
- public class SleuthExecutors {
- @Async
- public void go(){
- log.info("go");
- }
- }
- @RestController
- @Slf4j
- public class LizzController {
- @Autowired
- SleuthExecutors sleuthExecutors;
- @GetMapping("/asyncSleuth")
- public void asyncSleuth() {
- sleuthExecutors.go();
- }
- }
使用TraceRunnable
- @Slf4j
- @Service
- public class SleuthExecutors implements Runnable {
- @Override
- public void run() {
- log.info("go");
- }
- }
- @RestController
- @Slf4j
- public class LizzController {
- @Autowired
- Tracing tracing;
- public static final ExecutorService executorService = Executors.newFixedThreadPool(5);
- @GetMapping("/traceRunnable")
- public void traceRunnable() {
- log.info("traceRunnable");
- // 线程加入到tracing中
- Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
- .wrap(sleuthExecutors);
- executorService.submit(traceRunnableFromTracer);
- }
-
- }