编程语言
首页 > 编程语言> > java-如何在CompletableFuture中保留slf4j MDC日志记录上下文?

java-如何在CompletableFuture中保留slf4j MDC日志记录上下文?

作者:互联网

执行异步CompletableFuture时,父线程上下文以及org.slf4j.MDC上下文都会丢失.

这很不好,因为我使用某种“鱼标记”来跟踪多个日志文件中一个请求的日志.

MDC.put(“ fishid”,randomId())

问题:一般来说,在CompletableFutures的任务期间,如何保留该ID?

List<CompletableFuture<UpdateHotelAllotmentsRsp>> futures =
    tasks.stream()
        .map(task -> CompletableFuture.supplyAsync(
            () -> businesslogic(task))
        .collect(Collectors.toList());

List results = futures.stream()
    .map(CompletableFuture::join)
    .collect(Collectors.toList());

public void businesslogic(Task task) {
       LOGGER.info("mdc fishtag context is lost here");
}

解决方法:

最后,我创建了一个保留MDC的Supplier包装器.如果有人有更好的主意,请随时发表评论.

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) {
    return CompletableFuture.supplyAsync(new SupplierMDC(supplier), executor);
}

private static class SupplierMDC<T> implements Supplier<T> {
    private final Supplier<T> delegate;
    private final Map<String, String> mdc;

    public SupplierMDC(Supplier<T> delegate) {
        this.delegate = delegate;
        this.mdc = MDC.getCopyOfContextMap();
    }

    @Override
    public T get() {
        MDC.setContextMap(mdc);
        return delegate.get();
    }
}

标签:completable-future,slf4j,mdc,java
来源: https://codeday.me/bug/20191109/2012526.html