业务要求流程流转与数据记录(插表)异步进行
使用线程池实现异步调用:
1.线程池配置
<bean id ="taskExecutor" name="esg.TaskExecutor" class ="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
<property name = "corePoolSize" value ="5" />
<property name = "keepAliveSeconds" value ="600" /> ---空闲线程的存活时间.
<property name = "maxPoolSize" value ="10" />
<property name = "queueCapacity" value ="25" />
</bean>`
A.CorePool Size:設定ThreadPool可接受的主要Thread数量
因此若ActiveThread未超過CorePool Size,則ThreadPool会继续New Thread
B.QueueCapacity:設定當Request超過CorePool Size時,可以先暂存的数量
因此若Request已經超過CorePool Size,則ThreadPool不會再New Thread,會先將Request放置於ArrayBlockingQueue
若此設定不為正整数,則ThreadPool会采用沒有限制的LinkedBlockingQueue,同時會忽略MaxPool Size的設定,也就是說Thread会无限制产生下去
C.MaxPool Size:設定當Queue满的時候,最大Thread的数量
因此若Request超過CorePool Size,會先放入Queue中保存,若連Queue都滿了,這時候ThreadPool會再New Thread,直到等於MaxPool Size
當Request量牴觸到MaxPool Size時,ThreadPool會將後續Request丟掉,可以實作RejectedExecutionHandler來承接這些被丟掉的Request,後續再看看是要記錄到資料庫或進行其他處置
参阅:http://blog.csdn.net/welken/article/details/5530001
2.
@Resource(name = "esg.TaskExecutor")
private TaskExecutor taskExecutor = null;
@Transactional(rollbackFor = Exception.class)
@Override
public void startInstanceAsync(final Input input, final Output output) {
taskExecutor.execute(new Runnable() {
public void run() {
Logger.trace(this.getClass(), "startInstanceAsync", "开始启动后台线程,启动实例化...");
try {
//数据持久化
}
catch (RuntimeException e) {
Logger.trace(this.getClass(), "startInstanceAsync", "线程处理异常." + e.getLocalizedMessage());
}
Logger.trace(this.getClass(), "startInstanceAsync", "启动实例化处理完成,线程结束");
}
});
}