我有一个运行许多异步过程的应用程序,可能需要十到二十分钟。
出错时,我使用只写日志错误的AsyncUncaughtExceptionHandler。我需要通知用户发生了错误。
现在我正在使用“DelegatingSecurityContextAsyncTaskExecutor”,它在线程之间共享spring安全性用户。但是当我注销时,它被删除,上下文中的用户为null。
这对我来说不行,我希望运行该方法的用户,而不是上下文中的当前用户,我需要他向您的个人邮箱发送邮件。
如何让用户执行该方法?
我的代码:
@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer {
@Override
@Bean(name = "asyncExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(1);
executor.setThreadGroupName("MyCustomExecutor");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setBeanName("asyncExecutor");
executor.initialize();
DelegatingSecurityContextAsyncTaskExecutor securityExecutor = new DelegatingSecurityContextAsyncTaskExecutor(executor);
return securityExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
private static final Logger LOG = LogManager.getLogger(CustomAsyncExceptionHandler.class);
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
LOG.error(
String.format("Error in async method %s with params: %s: Excepcion: %s",
method.getName(), params.toString(), ExceptionUtils.getStackTrace(ex)), ex);
}
}