提交 6d702c2a 编写于 作者: 武汉红喜's avatar 武汉红喜

MDCTool

上级 7b0a613c
package org.hongxi.whatsmars.common.mdc;
import org.slf4j.MDC;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Created by shenhongxi on 2020/8/16.
*/
public class MDCCallable<V> implements Callable<V> {
private final Callable<V> callable;
private transient final Map<String, String> _cm = MDC.getCopyOfContextMap();
public MDCCallable(Callable<V> callable) {
this.callable = callable;
}
@Override
public V call() throws Exception {
if (_cm != null) {
MDC.setContextMap(_cm);
}
try {
return callable.call();
} finally {
MDC.clear();
}
}
}
\ No newline at end of file
package org.hongxi.whatsmars.common.mdc;
import org.slf4j.MDC;
import java.util.Map;
/**
* Created by shenhongxi on 2020/8/16.
*/
public class MDCRunnable implements Runnable {
private final Runnable runnable;
private transient final Map<String, String> _cm = MDC.getCopyOfContextMap();
public MDCRunnable(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
if (_cm != null) {
MDC.setContextMap(_cm);
}
try {
runnable.run();
} finally {
MDC.clear();
}
}
}
\ No newline at end of file
package org.hongxi.whatsmars.common.mdc;
import org.slf4j.MDC;
import java.util.Map;
import java.util.function.Supplier;
/**
* Created by shenhongxi on 2020/8/16.
*/
public class MDCSupplier<T> implements Supplier<T> {
private transient final Map<String, String> _cm = MDC.getCopyOfContextMap();
private final Supplier<T> supplier;
public MDCSupplier(Supplier<T> supplier) {
this.supplier = supplier;
}
@Override
public T get() {
if (_cm != null) {
MDC.setContextMap(_cm);
}
try {
return supplier.get();
} finally {
MDC.clear();
}
}
}
\ No newline at end of file
package org.hongxi.whatsmars.common.mdc;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Created by shenhongxi on 2020/8/16.
*/
public final class MDCTool {
public static <T> MDCSupplier<T> supplier(Supplier<T> supplier) {
return new MDCSupplier<>(supplier);
}
public static MDCRunnable runnable(Runnable runnable) {
return new MDCRunnable(runnable);
}
public static MDCRunnable runnable(Consumer<Void> consumer) {
return new MDCRunnable(() -> {
consumer.accept(null);
});
}
public static <V> MDCCallable<V> callable(Callable<V> callable) {
return new MDCCallable<>(callable);
}
public static <V> MDCCallable<V> callable(Supplier<V> supplier) {
return new MDCCallable<>(() -> supplier.get());
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册