Java 触发异步线程后,Spring引导从应用程序注销
我使用模块化maven spring启动应用程序,最近在其中添加了redis集成。 为了与异步线程共享LoclContext、SecurityContext和MDC上下文,我在核心maven引导项目中添加了一个decoratorJava 触发异步线程后,Spring引导从应用程序注销,java,multithreading,spring-boot,spring-security,redis,Java,Multithreading,Spring Boot,Spring Security,Redis,我使用模块化maven spring启动应用程序,最近在其中添加了redis集成。 为了与异步线程共享LoclContext、SecurityContext和MDC上下文,我在核心maven引导项目中添加了一个decorator public class ContextAwareTaskDecorator implements TaskDecorator { @Override public Runnable decorate(Runnable runnable) { // R
public class ContextAwareTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
// Right now: Web thread context !
// (Grab the current thread MDC data)
Map<String, String> contextMap = MDC.getCopyOfContextMap();
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
Locale locale = LocaleContextHolder.getLocale();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return () -> {
try {
// Right now: @Async thread context !
// (Restore the Web thread context's MDC data)
if (contextMap != null) {
MDC.setContextMap(contextMap);
}
if (locale != null) {
LocaleContextHolder.setLocale(locale, true);
}
if (attributes != null) {
RequestContextHolder.setRequestAttributes(attributes, true);
}
if(authentication != null) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
runnable.run();
} finally {
MDC.clear();
LocaleContextHolder.resetLocaleContext();
RequestContextHolder.resetRequestAttributes();
SecurityContextHolder.clearContext();
}
};
}
}
现在,当我执行一个特定的请求时,我正在使用@Async触发方法,它可以正常工作,但在那之后,如果我单击任何链接或选项卡,将我抛出我的应用程序,并且我被重定向到登录页面,那么任何类型的日志中都没有错误
我试着在decorator中评论这行代码,它重置了所有上下文并清除了MDC,即使在这之后我也面临着同样的问题
如果我删除了redis依赖项,那么一切都正常
有人能告诉我是什么原因造成的吗
@Configuration
@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {
private static final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(300);
executor.setQueueCapacity(1000);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setTaskDecorator(new ContextAwareTaskDecorator());
executor.setThreadNamePrefix("my-executor-");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}