这样能够避免堵塞、以及保证任务的实时性。适用于处理log、发送邮件、短信……等。
<!-- 缺省的异步任务线程池 --> <task:annotation-driven executor="asyncExecutor" /> <task:executor id="asyncExecutor" pool-size="100-10000" queue-capacity="10" /> <!-- 处理log的线程池 --> <task:executor id="logExecutor" pool-size="15-1000" queue-capacity="5" keep-alive="5"/>
@Override
@Async("logExecutor") //假设不指定名字。会使用缺省的“asyncExecutor”
public void saveUserOpLog(TabUserOpLog tabUserOpLog) {
userOpLogDAO.insertTabUserOpLog(tabUserOpLog);
}(注意:假设在同一个类中调用的话。不会生效,原因请參考:http://blog.csdn.net/clementad/article/details/47339519)然而,线程池中已经在执行的任务。因为缺省是用户线程,所以JVM会等待它们结束后才退出。
@Configuration
@EnableAsync
public class SpringConfig {
/** Set the ThreadPoolExecutor‘s core pool size. */
private int corePoolSize = 10;
/** Set the ThreadPoolExecutor‘s maximum pool size. */
private int maxPoolSize = 200;
/** Set the capacity for the ThreadPoolExecutor‘s BlockingQueue. */
private int queueCapacity = 10;
private String ThreadNamePrefix = "MyLogExecutor-";
@Bean
public Executor logExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(ThreadNamePrefix);
// rejection-policy:当pool已经达到max size的时候,怎样处理新任务
// CALLER_RUNS:不在新线程中运行任务。而是有调用者所在的线程来运行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}原文:http://www.cnblogs.com/tlnshuju/p/6955803.html