Spring 3中异步方法调用

10-01-14 banq
如今,异步 EDA是一个潮流,滚滚而来,让我们看看主流框架Spring 3.0新版本有没有顺应这新趋势,Asynchronous method invocation in Spring 3.0介绍了异步使用。

@Async让方法能够被异步调用,以及定时运行。如下:


@Component
public class MailUtility {

@Async
public void sendMail(String name){

    System.out.println(” I Will be formatting html mail and sending it  “);

try {
    Thread.sleep(10000);

} catch (InterruptedException e) {

     e.printStackTrace();
}

System.out.println(” Asynchronous method call of send email — Complete “);

}

}
<p class="indent">


这里发送Email使用异步实现,从这个应用案例上看,Spring 3的异步只是体现在业务应用上。

而我们从最新强劲框架Akka可以看到,异步已经作为实现BASE架构思想扩散开来了,不只是针对个别确实需要异步的应用。Jdon框架也将异步Domain Events作为领域模型指挥技术架构基础架构,相信Spring 3.0普及,有更多应用异步案例出现。

[该贴被banq于2010-01-14 10:19修改过]

cmzx3444
2010-01-14 13:43
@Async是怎么实现异步的啊,对类没有特别的要求吗,真的是太神奇了

ferendo
2010-01-15 10:21
If there is a lot of request invoking the async method,it will cause OutOfMemoryError.

How to control the thread number in the thread pool?Tks.

banq
2010-01-15 10:42
2010年01月15日 10:21 "ferendo"的内容
thread number in the thread pool


使用ThreadFixedPool来管理启动的线程。当然,这需要修改Spring框架源码,所以可见,框架本身的定制性也非常重要。不可能一个功能应付所有情况,尤其是其一些之前不被重视的功能,就可能没有预留拓展余地。

真正异步并发策略原理这么做:

使用future实现内置异步API

[该贴被banq于2010-01-19 11:39修改过]

netcasewqs
2010-04-12 12:47
2010年01月14日 13:43 "cmzx3444"的内容
@Async是怎么实现异步的啊,对类没有特别的要求吗,真的是太神奇了 ...



MailUtility 该类通过@Component注释告诉Spring容器该类需要被注册中,通过@Async告诉Spring容器该类需要一个Proxy类,把这个代理类注册到DI容器中,该代理类通过Future机制对SendMail方法进行一些包装,这样就把开发人员从异步编程中解脱出来了!

我是.Net开发人员,不知对Java的这种机制的理解是否正确,欢迎指正!