设计模式之装饰器模式

4 阅读1分钟

TaskDecorator

`@FunctionalInterface public interface TaskDecorator {

/**
 * Decorate the given {@code Runnable}, returning a potentially wrapped
 * {@code Runnable} for actual execution, internally delegating to the
 * original {@link Runnable#run()} implementation.
 * @param runnable the original {@code Runnable}
 * @return the decorated {@code Runnable}
 */
Runnable decorate(Runnable runnable);

}` 可以用于装饰线程池创建新线程传递父线程相关信息

例如打印日志时,线程池中的子线程常丢失日志的traceId(父线程相关信息) 可以使用该类进行实现:

public class MdcTaskDecorator implements TaskDecorator {

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

在线程池初始化中调用api,直接赋予子线程MDC相关的所有信息,不需要在子线程实现逻辑中,重复调用MDC相关api赋予值(例如traceId等)

threadPoolTaskExecutor.setTaskDecorator(new MdcTaskDecorator());