From fc469f0433469404ce054f9c6775edb019e57ad9 Mon Sep 17 00:00:00 2001 From: zlt Date: Sat, 17 Aug 2019 12:59:13 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=A7=9F=E6=88=B7=E5=92=8CMD?= =?UTF-8?q?C=E4=BF=A1=E6=81=AF=E7=9A=84=E7=88=B6=E5=AD=90=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E4=BC=A0=E9=80=92=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 6 + .../utils/CustomThreadPoolTaskExecutor.java | 90 ++------- .../common/utils/TenantContextHolder.java | 7 +- .../zlt-log-spring-boot-starter/pom.xml | 5 + .../log/config/TtlMDCAdapterInitializer.java | 19 ++ .../main/java/org/slf4j/TtlMDCAdapter.java | 188 ++++++++++++++++++ .../main/resources/META-INF/spring.factories | 3 + 7 files changed, 242 insertions(+), 76 deletions(-) create mode 100644 zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/TtlMDCAdapterInitializer.java create mode 100644 zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java diff --git a/pom.xml b/pom.xml index f85ff0e9..a707fa64 100644 --- a/pom.xml +++ b/pom.xml @@ -39,6 +39,7 @@ 5.0.2.RELEASE 1.26.5 1.21 + 2.11.0 Cairo-SR3 2.0.0.RELEASE 2.0.9.RELEASE @@ -297,6 +298,11 @@ UserAgentUtils ${userAgent.version} + + com.alibaba + transmittable-thread-local + ${transmittable.version} + org.springframework.boot diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java index 8eaa8872..88aaa93a 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java @@ -1,109 +1,49 @@ package com.central.common.utils; -import cn.hutool.core.util.StrUtil; -import org.slf4j.MDC; +import com.alibaba.ttl.TtlCallable; +import com.alibaba.ttl.TtlRunnable; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.concurrent.ListenableFuture; -import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** - * 这是{@link ThreadPoolTaskExecutor}的一个简单替换,可以在每个任务之前设置子线程的租户和MDC数据 + * 这是{@link ThreadPoolTaskExecutor}的一个简单替换,可搭配TransmittableThreadLocal实现父子线程之间的数据传递 * * @author zlt * @date 2019/8/14 */ public class CustomThreadPoolTaskExecutor extends ThreadPoolTaskExecutor { - /** - * 把父线程的租户和MDC内容赋值给子线程 - * @param runnable - */ + private static final long serialVersionUID = -5887035957049288777L; + @Override public void execute(Runnable runnable) { - String tenantId = TenantContextHolder.getTenant(); - Map mdcContext = MDC.getCopyOfContextMap(); - super.execute(() -> run(runnable, tenantId, mdcContext)); + Runnable ttlRunnable = TtlRunnable.get(runnable); + super.execute(ttlRunnable); } @Override public Future submit(Callable task) { - String tenantId = TenantContextHolder.getTenant(); - Map mdcContext = MDC.getCopyOfContextMap(); - return super.submit(() -> call(task, tenantId, mdcContext)); + Callable ttlCallable = TtlCallable.get(task); + return super.submit(ttlCallable); } @Override public Future submit(Runnable task) { - String tenantId = TenantContextHolder.getTenant(); - Map mdcContext = MDC.getCopyOfContextMap(); - return super.submit(() -> run(task, tenantId, mdcContext)); + Runnable ttlRunnable = TtlRunnable.get(task); + return super.submit(ttlRunnable); } @Override public ListenableFuture submitListenable(Runnable task) { - String tenantId = TenantContextHolder.getTenant(); - Map mdcContext = MDC.getCopyOfContextMap(); - return super.submitListenable(() -> run(task, tenantId, mdcContext)); + Runnable ttlRunnable = TtlRunnable.get(task); + return super.submitListenable(ttlRunnable); } @Override public ListenableFuture submitListenable(Callable task) { - String tenantId = TenantContextHolder.getTenant(); - Map mdcContext = MDC.getCopyOfContextMap(); - return super.submitListenable(() -> call(task, tenantId, mdcContext)); - } - - /** - * 子线程委托的执行方法 - * @param runnable {@link Runnable} - * @param tenantId 租户id - * @param mdcContext 父线程MDC内容 - */ - private void run(Runnable runnable, String tenantId, Map mdcContext) { - // 将父线程的租户id传给子线程 - if (StrUtil.isNotEmpty(tenantId)) { - TenantContextHolder.setTenant(tenantId); - } - // 将父线程的MDC内容传给子线程 - if (mdcContext != null) { - MDC.setContextMap(mdcContext); - } - try { - // 执行异步操作 - runnable.run(); - } finally { - // 清空租户内容 - TenantContextHolder.clear(); - // 清空MDC内容 - MDC.clear(); - } - } - - /** - * 子线程委托的执行方法 - * @param task {@link Callable} - * @param tenantId 租户id - * @param mdcContext 父线程MDC内容 - */ - private T call(Callable task, String tenantId, Map mdcContext) throws Exception { - // 将父线程的租户id传给子线程 - if (StrUtil.isNotEmpty(tenantId)) { - TenantContextHolder.setTenant(tenantId); - } - // 将父线程的MDC内容传给子线程 - if (mdcContext != null) { - MDC.setContextMap(mdcContext); - } - try { - // 执行异步操作 - return task.call(); - } finally { - // 清空租户内容 - TenantContextHolder.clear(); - // 清空MDC内容 - MDC.clear(); - } + Callable ttlCallable = TtlCallable.get(task); + return super.submitListenable(ttlCallable); } } diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/TenantContextHolder.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/TenantContextHolder.java index b21ee242..1df1319f 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/TenantContextHolder.java +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/TenantContextHolder.java @@ -1,5 +1,7 @@ package com.central.common.utils; +import com.alibaba.ttl.TransmittableThreadLocal; + /** * 租户holder * @@ -7,7 +9,10 @@ package com.central.common.utils; * @date 2019/8/5 */ public class TenantContextHolder { - private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + /** + * 支持父子线程之间的数据传递 + */ + private static final ThreadLocal CONTEXT = new TransmittableThreadLocal<>(); public static void setTenant(String tenant) { CONTEXT.set(tenant); diff --git a/zlt-commons/zlt-log-spring-boot-starter/pom.xml b/zlt-commons/zlt-log-spring-boot-starter/pom.xml index fc623dcc..fa2dc2b1 100644 --- a/zlt-commons/zlt-log-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-log-spring-boot-starter/pom.xml @@ -26,5 +26,10 @@ org.springframework.cloud spring-cloud-context + + + com.alibaba + transmittable-thread-local + diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/TtlMDCAdapterInitializer.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/TtlMDCAdapterInitializer.java new file mode 100644 index 00000000..1250d1ba --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/TtlMDCAdapterInitializer.java @@ -0,0 +1,19 @@ +package com.central.log.config; + +import org.slf4j.TtlMDCAdapter; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * 初始化TtlMDCAdapter实例,并替换MDC中的adapter对象 + * + * @author zlt + * @date 2019/8/17 + */ +public class TtlMDCAdapterInitializer implements ApplicationContextInitializer { + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + //加载TtlMDCAdapter实例 + TtlMDCAdapter.getInstance(); + } +} \ No newline at end of file diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java new file mode 100644 index 00000000..a1df074b --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/org/slf4j/TtlMDCAdapter.java @@ -0,0 +1,188 @@ +package org.slf4j; + +import ch.qos.logback.classic.util.LogbackMDCAdapter; +import com.alibaba.ttl.TransmittableThreadLocal; +import org.slf4j.spi.MDCAdapter; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * 重构{@link LogbackMDCAdapter}类,搭配TransmittableThreadLocal实现父子线程之间的数据传递 + * + * @author zlt + * @date 2019/8/17 + */ +public class TtlMDCAdapter implements MDCAdapter { + private final ThreadLocal> copyOnInheritThreadLocal = new TransmittableThreadLocal<>(); + + private static final int WRITE_OPERATION = 1; + private static final int MAP_COPY_OPERATION = 2; + + private static TtlMDCAdapter mtcMDCAdapter; + + /** + * keeps track of the last operation performed + */ + private final ThreadLocal lastOperation = new ThreadLocal<>(); + + static { + mtcMDCAdapter = new TtlMDCAdapter(); + MDC.mdcAdapter = mtcMDCAdapter; + } + + public static MDCAdapter getInstance() { + return mtcMDCAdapter; + } + + private Integer getAndSetLastOperation(int op) { + Integer lastOp = lastOperation.get(); + lastOperation.set(op); + return lastOp; + } + + private static boolean wasLastOpReadOrNull(Integer lastOp) { + return lastOp == null || lastOp == MAP_COPY_OPERATION; + } + + private Map duplicateAndInsertNewMap(Map oldMap) { + Map newMap = Collections.synchronizedMap(new HashMap<>()); + if (oldMap != null) { + // we don't want the parent thread modifying oldMap while we are + // iterating over it + synchronized (oldMap) { + newMap.putAll(oldMap); + } + } + + copyOnInheritThreadLocal.set(newMap); + return newMap; + } + + /** + * Put a context value (the val parameter) as identified with the + * key parameter into the current thread's context map. Note that + * contrary to log4j, the val parameter can be null. + *

+ *

+ * If the current thread does not have a context map it is created as a side + * effect of this call. + * + * @throws IllegalArgumentException in case the "key" parameter is null + */ + @Override + public void put(String key, String val) { + if (key == null) { + throw new IllegalArgumentException("key cannot be null"); + } + + Map oldMap = copyOnInheritThreadLocal.get(); + Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); + + if (wasLastOpReadOrNull(lastOp) || oldMap == null) { + Map newMap = duplicateAndInsertNewMap(oldMap); + newMap.put(key, val); + } else { + oldMap.put(key, val); + } + } + + /** + * Remove the the context identified by the key parameter. + *

+ */ + @Override + public void remove(String key) { + if (key == null) { + return; + } + Map oldMap = copyOnInheritThreadLocal.get(); + if (oldMap == null) { + return; + } + + Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); + + if (wasLastOpReadOrNull(lastOp)) { + Map newMap = duplicateAndInsertNewMap(oldMap); + newMap.remove(key); + } else { + oldMap.remove(key); + } + + } + + + /** + * Clear all entries in the MDC. + */ + @Override + public void clear() { + lastOperation.set(WRITE_OPERATION); + copyOnInheritThreadLocal.remove(); + } + + /** + * Get the context identified by the key parameter. + *

+ */ + @Override + public String get(String key) { + final Map map = copyOnInheritThreadLocal.get(); + if ((map != null) && (key != null)) { + return map.get(key); + } else { + return null; + } + } + + /** + * Get the current thread's MDC as a map. This method is intended to be used + * internally. + */ + public Map getPropertyMap() { + lastOperation.set(MAP_COPY_OPERATION); + return copyOnInheritThreadLocal.get(); + } + + /** + * Returns the keys in the MDC as a {@link Set}. The returned value can be + * null. + */ + public Set getKeys() { + Map map = getPropertyMap(); + + if (map != null) { + return map.keySet(); + } else { + return null; + } + } + + /** + * Return a copy of the current thread's context map. Returned value may be + * null. + */ + @Override + public Map getCopyOfContextMap() { + Map hashMap = copyOnInheritThreadLocal.get(); + if (hashMap == null) { + return null; + } else { + return new HashMap<>(hashMap); + } + } + + @Override + public void setContextMap(Map contextMap) { + lastOperation.set(WRITE_OPERATION); + + Map newMap = Collections.synchronizedMap(new HashMap<>()); + newMap.putAll(contextMap); + + // the newMap replaces the old one for serialisation's sake + copyOnInheritThreadLocal.set(newMap); + } +} diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories index 7a25cdef..25b1a4a8 100644 --- a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -1,2 +1,5 @@ +org.springframework.context.ApplicationContextInitializer=\ +com.central.log.config.TtlMDCAdapterInitializer + org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.central.log.config.LogAutoConfigure