原文:http://www.cnblogs.com/zhengbin/p/6104502.html

简单介绍:

Spring为任务调度与异步方法执行提供了注解支持。通过在方法上设置@Async注解,可使得方法被异步调用。也就是说调用者会在调用时立即返回,而被调用方法的实际执行是交给Spring的TaskExecutor来完成。

开启@Async注解:

<task:annotation-driven executor="annotationExecutor" />
<!-- 支持 @Async 注解 -->
<task:executor id="annotationExecutor" pool-size="20"/>

同时加入<context:component-scan />扫描注解。

栗子:

为了比较,先来一个同步调用:

Component
public class TestAsyncBean {
public void sayHello4() throws InterruptedException {
Thread.sleep(2 * 1000);//网络连接中 。。。消息发送中。。。
System.out.println("我爱你啊!");
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/applicationContext.xml"})
public class TestAsync {
@Test
public void test_sayHello4() throws InterruptedException, ExecutionException {
System.out.println("你不爱我了么?");
testAsyncBean.sayHello4();
System.out.println("回的这么慢, 你肯定不爱我了, 我们还是分手吧。。。");
Thread.sleep(3 * 1000);// 不让主进程过早结束
}
}

输出结果:

你不爱我了么?
我爱你啊!
回的这么慢, 你肯定不爱我了, 我们还是分手吧。。。

同步调用会按代码顺序依次进行下去,如果哪里需要等待,那么就阻塞在那里,不再向下继续进行。

使用@Async的异步调用:

@Component
public class TestAsyncBean {
@Async
public void sayHello3() throws InterruptedException {
Thread.sleep(2 * 1000);//网络连接中 。。。消息发送中。。。
System.out.println("我爱你啊!");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/applicationContext.xml"})
public class TestAsync {
@Autowired
private TestAsyncBean testAsyncBean;
@Test
public void test_sayHello3() throws InterruptedException, ExecutionException {
System.out.println("你不爱我了么?");
testAsyncBean.sayHello3();
System.out.println("你竟无话可说, 我们分手吧。。。");
Thread.sleep(3 * 1000);// 不让主进程过早结束
}
}

输出结果:

你不爱我了么?
你竟无话可说, 我们分手吧。。。
我爱你啊!

异步调用,通过开启新的线程来执行调用的方法,不影响主线程。异步方法实际的执行交给了Spring的TaskExecutor来完成。

上面这种方式是没有返回值的,下面尝试有返回值的异步调用:

@Component
public class TestAsyncBean {
@Async
public String sayHello2() throws InterruptedException {
Thread.sleep(2 * 1000);//网络连接中 。。。消息发送中。。。
return "我爱你啊!";// 调用方调用后会立即返回,所以返回null
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/applicationContext.xml"})
public class TestAsync {
@Autowired
private TestAsyncBean testAsyncBean;
@Test
public void test_sayHello2() throws InterruptedException, ExecutionException {
System.out.println("你不爱我了么?");
System.out.println(testAsyncBean.sayHello2());
System.out.println("你说的啥? 我们还是分手吧。。。");
Thread.sleep(3 * 1000);// 不让主进程过早结束
}
}

输出结果:

你不爱我了么?
null
你说的啥? 我们还是分手吧。。。

通过直接获取返回值得方式是不行的,这里就需要用到异步回调,异步方法返回值必须为Future<>,就像Callable与Future。

下面通过AsyncResult<>来获得异步调用的返回值:

@Component
public class TestAsyncBean {
@Async
public Future<String> sayHello1() throws InterruptedException {
int thinking = 2;
Thread.sleep(thinking * 1000);//网络连接中 。。。消息发送中。。。
System.out.println("我爱你啊!");
return new AsyncResult<String>("发送消息用了"+thinking+"秒");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/applicationContext.xml"})
public class TestAsync {
@Autowired
private TestAsyncBean testAsyncBean;
@Test
public void test_sayHello1() throws InterruptedException, ExecutionException {
Future<String> future = null;
System.out.println("你不爱我了么?");
future = testAsyncBean.sayHello1();
System.out.println("你竟无话可说, 我们分手吧。。。");
Thread.sleep(3 * 1000);// 不让主进程过早结束
System.out.println(future.get());
}
}

输出结果:

你不爱我了么?
你竟无话可说, 我们分手吧。。。
我爱你啊!
发送消息用了2秒

Spring中@Async注解实现“方法”的异步调用的更多相关文章

  1. 使用Spring中@Async注解实现异步调用

    异步调用? 在解释异步调用之前,我们先来看同步调用的定义:同步就是整个处理过程顺序执行,当各个过程都执行完毕,并返回结果. 异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕,继 ...

  2. Spring中@Async用法详解及简单实例

    Spring中@Async用法 引言: 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类 ...

  3. SpringCloud 微服务中 @Async 注解自定义线程池 引发的aop 问题

    背景 在 使用springCloud 的@Async注解来做异步操作时,想自定义其线程池. 引发问题 自定义完线程池后,发现代码里并没有使用自定义线程池里的线程,于是新建一个demo工程,一样的配置代 ...

  4. 【转】Spring中@Async

    Spring中@Async 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实, ...

  5. Spring中Value注解的使用

    Spring中Value注解的使用 分类: Spring2014-08-16 17:28 2985人阅读 评论(0) 收藏 举报 有的时候我们定义了Properties文件,并且使用Spring的Pr ...

  6. 全面解析Spring中@ModelAttribute注解的用法

    本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:全面解析Spring中@ModelAttribute注解的用法: @ModelAttribute注解用于将方法的参数或方法的返回值绑定到 ...

  7. Spring中常用注解的介绍

    spring中使用注解时配置文件的写法: <?xml version="1.0" encoding="UTF-8"?> <span style ...

  8. Spring中@Import注解的使用

    Spring中@Import注解的使用 @Import注解算是SpringBoot自动配置原理中一个很重要的注解 认识@Import注解 先看一下源码 @Target(ElementType.TYPE ...

  9. Spring中常用注解

    1.@Component 创建类对象,相当于配置<bean/> 2.@Service @Service与@Component功能相同,写在ServiceImpl类上 3.@Reposito ...

随机推荐

  1. RESTful使用

    测试工具: JMeter 可以使用JMeter对HTTP REST接口进行测试 Java RESTful框架: Jersey

  2. JQuery html API支持解析执行Javascript脚本功能实现-代码分析

    JQuery html用法(功能类似innerHTML) 开发中需要使用Ajax技术来更新页面局部区域, 使用的方法是ajax获取html代码段(字符串),然后将这个html代码段作为参数,传入目标D ...

  3. 关于 Android 5.0 原生系统网络图标上的感叹号问题解决方法

    解决方案 adb shell settings put global captive_portal_server g.cn 参考 关于 android 5.0 网络图标上的感叹号及其解决办法

  4. Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least one of these environment variable is needed to run this program

    开启tomcat时出现以上错误 // 进入root帐户 在普通用户也可以 sudo -s //用编辑器打开.bashrc文件 gedit .bashrc 在普通用户下注意加上sudo //在最后一行添 ...

  5. EBS R12.2 创建应用层的启动和关闭脚本

    Create the following files to start and stop R12. application tier. Change the apps and weblogic pas ...

  6. [原创]如何设计Lighthoused定位接收电路

    本文使用最新出来的专用芯片TS3633 1)电路设计说明 1.电源电路 利用LM317低线性稳压芯片将5V或者12V的电源电压稳压到3.3V为TS3633提供工作电压.其中,磁珠L1主要用于抑制电源线 ...

  7. 响应式布局1--媒体查询和-webkit-min-device-pixel-ratio

    -webkit-min-device-pixel-ratio其实就是这个玩意 window.devicePixelRatio是设备上物理像素和设备独立像素(device-independent pix ...

  8. 。。。在学习新框架Spring MVC的感受。。。

    已经学习一遍Spring MVC了,感觉还是懵懵懂懂的,特别是重定向,路径,参数的这些问题,心好乱,不过,这,都不是问题!!! 继续努力,努力到会为止!!!加油!!!

  9. IPC

    IPC,全名Inter Process Communication即进程间通讯,在同一台机器上的两个进程就用IPC,不能跨物理机器。IPC包括共享内存、队列、信号量等几种方式,由于IPC通讯效率之高, ...

  10. phpcms V9 添加模块

    为phpcms创建一个模块的开发流程 [1]创建模块目录 通过前面的学习,我们已经知道phpcms V9框架中的模块位于phcms/modules目录中,每一个目录称之为一个模块. 如果要创建一个模块 ...