All Downloads are FREE. Search and download functionalities are using the official Maven repository.

club.zhcs.lina.trace.thread.ThreadMdcUtil Maven / Gradle / Ivy

The newest version!
package club.zhcs.lina.trace.thread;

import java.util.Map;
import java.util.concurrent.Callable;

import org.slf4j.MDC;

import club.zhcs.lina.trace.Constants;
import club.zhcs.lina.trace.TraceIdUtil;
import lombok.experimental.UtilityClass;

@UtilityClass
public class ThreadMdcUtil {

	public static void setTraceIdIfAbsent() {
		if (MDC.get(Constants.TRACE_ID) == null) {
			MDC.put(Constants.TRACE_ID, TraceIdUtil.getTraceId());
		}
	}

	public static  Callable wrap(final Callable callable, final Map context) {
		return () -> {
			if (context == null) {
				MDC.clear();
			} else {
				MDC.setContextMap(context);
			}
			setTraceIdIfAbsent();
			try {
				return callable.call();
			} finally {
				MDC.clear();
			}
		};
	}

	public static Runnable wrap(final Runnable runnable, final Map context) {
		return () -> {
			if (context == null) {
				MDC.clear();
			} else {
				MDC.setContextMap(context);
			}
			setTraceIdIfAbsent();
			try {
				runnable.run();
			} finally {
				MDC.clear();
			}
		};
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy