package com.malk.core;

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

/**
 * 把主线程的 MDC 拷贝到 @Async 子线程，避免 traceId 丢失。
 * -
 * 用法：在 ThreadPoolTaskExecutor 上 setTaskDecorator(new MdcTaskDecorator())
 */
public class MdcTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> context = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (context != null) {
                    MDC.setContextMap(context);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
