您可以将 ThreadPoolTaskExecutor 包装在一个自定义类中,该类将安排对任务状态的验证,如果未完成则将其取消。
public class CancellingExecutor implements Executor {
private final ExecutorService delegate;
private final ScheduledExecutorService monitoringExecutor;
public CancellingExecutor(final ExecutorService delegate,
final ScheduledExecutorService monitoringExecutor) {
this.delegate = delegate;
this.monitoringExecutor = monitoringExecutor;
}
@Override
public void execute(final Runnable command) {
Future<?> future = delegate.submit(command);
monitoringExecutor.schedule(() -> {
if (!future.isDone() && !future.isCancelled()) {
future.cancel(false);
}
}, 1, TimeUnit.MINUTES);
}
}
配置将如下所示:
@Bean("asyncExecutor")
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
executor.setThreadNamePrefix("threadPoolExecutor-");
executor.initialize();
ScheduledExecutorService monitoringExecutor = Executors.newScheduledThreadPool(1);
return new CancellingExecutor(executor, monitoringExecutor);
}