Spring3.x中的几个异步执行

1.servlet3

细节可以阅读http://www.ibm.com/developerworks/cn/java/j-lo-servlet30/
现在通过使用 Servlet 3.0 的异步处理支持,之前的 Servlet 处理流程可以调整为如下的过程:首先,Servlet 接收到请求之后,可能首先需要对请求携带的数据进行一些预处理;接着,Servlet 线程将请求转交给一个异步线程来执行业务处理,线程本身返回至容器,此时 Servlet 还没有生成响应数据,异步线程处理完业务以后,可以直接生成响应数据(异步线程拥有 ServletRequest 和 ServletResponse 对象的引用),或者将请求继续转发给其它 Servlet。如此一来, Servlet 线程不再是一直处于阻塞状态以等待业务逻辑的处理,而是启动异步线程之后可以立即返回。

 

总结起来,就是1.Servlet线程调用到另外的线程去执行方法,而自身线程将立即释放;节约了宝贵的tomcat并发连接数,也就是同时可以容纳更多的并发。  2.response还是需要等待新线程执行完方法返回的,也就是这个做法,并不会节约客户端的请求回应等待时间。

 

2.TaskExecutor

  private TaskExecutor taskExecutor;

  public TaskExecutorExample(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
  }

 这个东西是异步的么?也不一定。线程池提交,解决的是多个人一起去干活,但是单个活的耗时是无法节约的。看doc文档这么写

void org.springframework.core.task.TaskExecutor.execute(Runnable task)

Execute the given task.

The call might return immediately if the implementation uses an asynchronous execution strategy, or might block in the case of synchronous execution.

 

 

3.@Async 

真正的异步调用,调用方不等待函数的返回,最适用于需要立即返回的地方了。

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async

 

The @Async annotation can be provided on a method so that invocation of that method will occur asynchronously. In other words, the caller will return immediately upon invocation and the actual execution of the method will occur in a task that has been submitted to a Spring TaskExecutor. In the simplest case, the annotation may be applied to a void-returning method.
@Async
void doSomething() {
    // this will be executed asynchronously
}

需要返回的时候,必须单独处理 

 

 

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
} 

 

 

默认用于方法上,但是一样可以作用于spring的executor bean。Executor qualification with @Async 

@Async("otherExecutor")
void doSomething(String s) {
    // this will be executed asynchronously by "otherExecutor"
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值