Log4j 的 ThreadContext 会自动清除



我在应用程序开始时向ThreadContext映射中插入一个密钥,就像一样

protected void doFilterWrapped(ContentCachingRequestWrapper request,
ContentCachingResponseWrapper response, FilterChain filterChain)
throws ServletException, IOException {
// some code...
ThreadContext.put(Constants.REQUEST_ID, requestID);
ThreadContext.put(requestID + Constants.HASH + "retryCount", "-1");
// some more code...
}

现在在另一个类中,我正在尝试更新密钥requestID + Constants.HASH + "retryCount"的值,就像一样

String key = ThreadContext.get(Constants.REQUEST_ID) + Constants.HASH + "retryCount";
if (ThreadContext.containsKey(key)) {
ThreadContext.put(key, String.valueOf(Integer.valueOf(ThreadContext.get(key)) + 1));
} else {
ThreadContext.put(key, "-1");
}
System.out.println("nn  " + ThreadContext.get(key) + " nn");

但它只工作一次,之后就找不到key,即ThreadContext.containsKey(key)就是false

有人能解释一下问题出在哪里吗?

您尝试过设置ad上下文可继承系统属性吗?在您的应用程序启动中,添加此行:

System.setProperty("isThreadContextMapInheritable", "true");

启用此属性后,子线程将继承线程上下文。

最新更新