Spring中@Async注解实现“方法”的异步调用
原文: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注解实现“方法”的异步调用的更多相关文章
- 使用Spring中@Async注解实现异步调用
异步调用? 在解释异步调用之前,我们先来看同步调用的定义:同步就是整个处理过程顺序执行,当各个过程都执行完毕,并返回结果. 异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕,继 ...
- Spring中@Async用法详解及简单实例
Spring中@Async用法 引言: 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类 ...
- SpringCloud 微服务中 @Async 注解自定义线程池 引发的aop 问题
背景 在 使用springCloud 的@Async注解来做异步操作时,想自定义其线程池. 引发问题 自定义完线程池后,发现代码里并没有使用自定义线程池里的线程,于是新建一个demo工程,一样的配置代 ...
- 【转】Spring中@Async
Spring中@Async 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实, ...
- Spring中Value注解的使用
Spring中Value注解的使用 分类: Spring2014-08-16 17:28 2985人阅读 评论(0) 收藏 举报 有的时候我们定义了Properties文件,并且使用Spring的Pr ...
- 全面解析Spring中@ModelAttribute注解的用法
本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:全面解析Spring中@ModelAttribute注解的用法: @ModelAttribute注解用于将方法的参数或方法的返回值绑定到 ...
- Spring中常用注解的介绍
spring中使用注解时配置文件的写法: <?xml version="1.0" encoding="UTF-8"?> <span style ...
- Spring中@Import注解的使用
Spring中@Import注解的使用 @Import注解算是SpringBoot自动配置原理中一个很重要的注解 认识@Import注解 先看一下源码 @Target(ElementType.TYPE ...
- Spring中常用注解
1.@Component 创建类对象,相当于配置<bean/> 2.@Service @Service与@Component功能相同,写在ServiceImpl类上 3.@Reposito ...
随机推荐
- oracle 用户锁定及到期
select * from dba_users where username='HR'--查询用户状态 alter user HR identified by HR;--重新更新密码alter use ...
- 突然出现 -bash: pod: command not found 的解决方法
$ mkdir -p $HOME/Software/ruby $ export GEM_HOME=$HOME/Software/ruby $ gem install cocoapods [...] g ...
- Jmeter多机并发压测IP地址问题
meter.engine.RemoteJMeterEngineImpl: Local IP address=192.168.56.1 不能成功链家到相应的压力机 解决步骤: 1.找到jmeter.ba ...
- Rsyslog配置文件详解
Rsyslog配置文件详解https://my.oschina.net/0757/blog/198329 # Save boot messages also to boot.log 启动的相关信息lo ...
- magento -- 解决magento错误:ERROR: Base table or view already exists: 1050 Table ... already exists
相信有更新magento或者,备份转移magento站点的时候可能会碰到类似这样的错误提示: Base table or view already exists: 1050 Table ... alr ...
- zjuoj 3601 Unrequited Love
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3601 Unrequited Love Time Limit: 16 Sec ...
- poi jar包的作用
目前POI的最新发布版本是3.10_FINAL.该版本保护的jar包有: Maven artifactId Prerequisites JAR poi commons-logging, commons ...
- jsp中用EL读取了数据库里面的时间,怎么设置格式显示的格式
首先导入标签 <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> < ...
- :last-child
匹配最后一个子元素 :last只匹配最后一个元素,而此选择符将为每个父元素匹配最后一个子元素 示例 描述: 在每个 ul 中查找最后一个 li HTML 代码: <ul> <li&g ...
- fgets函数
打开文件 fopen("需要打开的路径") 然后使用fgets函数读取行 #include <stdio.h> #include <stdlib.h> #i ...