场景
在使用Sleuth做链路跟踪时,默认情况下异步线程会断链,需要进行代码调整支持。
调整内容
方式一
使用@Async实现异步线程
- 开启异步线程池
@EnableAsync
@SpringBootApplication
public class LizzApplication {public static void main(String[] args) {SpringApplication.run(LizzApplication.class, args);}
}
- 异步线程实现
@Slf4j
@Service
public class SleuthExecutors {@Asyncpublic void go(){log.info("go");}
}
- 调用异步线程
@RestController
@Slf4j
public class LizzController {@AutowiredSleuthExecutors sleuthExecutors; @GetMapping("/asyncSleuth")public void asyncSleuth() {sleuthExecutors.go();}
}
- 66cf4e9594b9f60c为父线程traceid,18a498dde65276ec为子线程traceid
方式二
使用TraceRunnable
- 自定线程
@Slf4j
@Service
public class SleuthExecutors implements Runnable {@Overridepublic void run() {log.info("go");}
}
- 自定义线程池
@RestController
@Slf4j
public class LizzController { @AutowiredTracing 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);}}
- 跨线程的同一个traceid