Spring异步任务处理,@Async的配置和使用
这样能够避免堵塞、以及保证任务的实时性。适用于处理log、发送邮件、短信……等。
- 类:表示这个类中的全部方法都是异步的
- 方法:表示这种方法是异步的,假设类也注解了。则以这种方法的注解为准
- executor:指定一个缺省的executor给@Async使用。
- id:当配置多个executor时,被@Async("id")指定使用;也被作为线程名的前缀。
- pool-size:
- core size:最小的线程数。缺省:1
- max size:最大的线程数,缺省:Integer.MAX_VALUE
- queue-capacity:当最小的线程数已经被占用满后,新的任务会被放进queue里面,当这个queue的capacity也被占满之后,pool里面会创建新线程处理这个任务。直到总线程数达到了max size,这时系统会拒绝这个任务并抛出TaskRejectedException异常(缺省配置的情况下,能够通过rejection-policy来决定怎样处理这样的情况)。缺省值为:Integer.MAX_VALUE
- keep-alive:超过core size的那些线程,任务完毕后,再经过这个时长(秒)会被结束掉
- rejection-policy:当pool已经达到max size的时候,怎样处理新任务
- ABORT(缺省):抛出TaskRejectedException异常,然后不运行
- DISCARD:不运行,也不抛出异常
- DISCARD_OLDEST:丢弃queue中最旧的那个任务
- CALLER_RUNS:不在新线程中运行任务,而是有调用者所在的线程来运行
<!-- 缺省的异步任务线程池 --> <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;
}
}

浙公网安备 33010602011771号