什么是异步调用

“异步调用”对应的是“同步调用”,同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行;异步调用指程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序。

同步调用

下面通过一个简单示例来直观的理解什么是同步调用:

定义Task类,创建三个处理函数分别模拟三个执行任务的操作,操作消耗时间随机取(10秒内)

package com.dxz.demo1;

import java.util.Random;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping; /**
* 定义3个任务
*/
@Component
public class Task1 { // 定义一个随机对象.
public static Random random = new Random(); // 任务一;
public void doTaskOne() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
} // 任务二;
public void doTaskTwo() throws Exception {
System.out.println("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
} // 任务3;
public void doTaskThree() throws Exception {
System.out.println("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
} }

编写一个访问方法:

package com.dxz.demo1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.dxz.HelloApplication; @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = HelloApplication.class)
public class Task1Test { @Autowired
private Task1 task1; //测试task1.
@Test
public void task1() throws Exception{
task1.doTaskOne();
task1.doTaskTwo();
task1.doTaskThree();
}
}

运行可以看到类似如下输出:

开始做任务一
2017-04-28 18:02:57.397 WARN 11016 --- [cTaskExecutor-1] o.s.a.r.l.SimpleMessageListenerContainer : Consumer raised exception, processing can restart if the connection factory supports it. Exception summary: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-04-28 18:02:57.398 INFO 11016 --- [cTaskExecutor-1] o.s.a.r.l.SimpleMessageListenerContainer : Restarting Consumer: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0
完成任务一,耗时:7740毫秒
开始做任务二
完成任务二,耗时:723毫秒
开始做任务三
2017-04-28 18:03:03.415 WARN 11016 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Consumer raised exception, processing can restart if the connection factory supports it. Exception summary: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-04-28 18:03:03.415 INFO 11016 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Restarting Consumer: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0
完成任务三,耗时:5047毫秒

异步调用

上述的同步调用虽然顺利的执行完了三个任务,但是可以看到执行时间比较长,若这三个任务本身之间不存在依赖关系,可以并发执行的话,同步调用在执行效率方面就比较差,可以考虑通过异步调用的方式来并发执行。

在Spring Boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数,Task类改在为如下模式:

package com.dxz.demo1;

import java.util.Random;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping; /**
* 定义3个任务
*/
@Component
public class Task2 { // 定义一个随机对象.
public static Random random = new Random(); // 任务一;
@Async
public void doTaskOne() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
} // 任务二;
@Async
public void doTaskTwo() throws Exception {
System.out.println("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
} // 任务3;
@Async
public void doTaskThree() throws Exception {
System.out.println("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
} }

为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:

package com.dxz;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}

编写测试方法:

package com.dxz.demo1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping; import com.dxz.HelloApplication; @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = HelloApplication.class)
public class Task2Test { @Autowired
private Task2 task2; //测试task1.
@Test
public void task1() throws Exception{
task2.doTaskOne();
task2.doTaskTwo();
task2.doTaskThree();
}
}

此时可以反复执行单元测试,您可能会遇到各种不同的结果,比如:

开始做任务一
开始做任务二
开始做任务三

修改下测试类:

package com.dxz.demo1;

import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping; import com.dxz.HelloApplication; @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = HelloApplication.class)
public class Task2Test { @Autowired
private Task2 task2; // 测试task1.
@Test
public void task1() throws Exception {
task2.doTaskOne();
task2.doTaskTwo();
task2.doTaskThree(); System.out.println("i'm here");
TimeUnit.SECONDS.sleep(15);
System.out.println("over");
} }

jieguo:

i'm here
开始做任务二
开始做任务一
开始做任务三
完成任务三,耗时:1280毫秒
2017-04-28 18:25:36.936 WARN 17848 --- [cTaskExecutor-1] o.s.a.r.l.SimpleMessageListenerContainer : Consumer raised exception, processing can restart if the connection factory supports it. Exception summary: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-04-28 18:25:36.938 INFO 17848 --- [cTaskExecutor-1] o.s.a.r.l.SimpleMessageListenerContainer : Restarting Consumer: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0
完成任务一,耗时:4951毫秒
完成任务二,耗时:7451毫秒
2017-04-28 18:25:42.971 WARN 17848 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Consumer raised exception, processing can restart if the connection factory supports it. Exception summary: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-04-28 18:25:42.972 INFO 17848 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Restarting Consumer: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0
over

Spring @Async实现异步调用示例的更多相关文章

  1. spring boot中使用@Async实现异步调用任务

    本篇文章主要介绍了spring boot中使用@Async实现异步调用任务,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 什么是“异步调用”? “异步调用”对应的是“同步 ...

  2. Spring Boot使用@Async实现异步调用

    原文:http://blog.csdn.net/a286352250/article/details/53157822 项目GitHub地址 : https://github.com/FrameRes ...

  3. spring boot 学习(十一)使用@Async实现异步调用

    使用@Async实现异步调用 什么是”异步调用”与”同步调用” “同步调用”就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行:”异步调用”则是只要上一行代码执行,无需等 ...

  4. Spring @Async开启异步任务

    1. 开启异步 @SpringBootApplication @EnableAsync //开启异步任务 public class Application { @Bean(name="pro ...

  5. C#中异步调用示例与详解

    using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...

  6. Spring @Async之一:实现异步调用示例

    什么是“异步调用”? “异步调用”对应的是“同步调用”,同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行:异步调用指程序在顺序执行时,不等待异步调用的语句返回结果 ...

  7. 56. spring boot中使用@Async实现异步调用【从零开始学Spring Boot】

    什么是"异步调用"? "异步调用"对应的是"同步调用",同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执 ...

  8. Spring Boot中使用@Async实现异步调用,加速任务的执行!

    什么是"异步调用"?"异步调用"对应的是"同步调用",同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行 ...

  9. Spring Boot中使用@Async实现异步调用

    在Spring Boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数,为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsyn ...

随机推荐

  1. 关于 transparent rgba display:none; opacity visiblity 关于em

    关于 transparent  rgba   display:none; opacity   visiblity   display 之后不会占位. 其余都会占位 opacity 还会继承,子元素也会 ...

  2. PTA——简单计算器

    PTA 7-20 简单计算器 #include<stdio.h> int main() { int a,b; char c; scanf("%d",&a); w ...

  3. this语句的第三、四点

    接着上次的继续更新  up~` 第三点主体怎么找? 就在这个函数(方法)带不带“.”,如果函数和方法执行带“.”,那么this就指向“.”前面的对象,如果不带“.”就指向window. 第四点自执行函 ...

  4. manjaro运行virtualbox报错

    manjaro运行virtualbox报错manjaro使用添加删除程序搜索virtualbox安装后运行报错, 安装过程有选择modules的过程(这里要选择匹配当前系统内核的版本),当时不了解是干 ...

  5. 实验吧—密码学——WP之 困在栅栏里的凯撒

    首先我们研究题目.栅栏:凯撒 还发现一个数字“6”,那么我们很容易就有一个解题思路 对这段字符进行栅栏解密再进行凯撒解密 我们都知道,栅栏解密的关键就是栏数,根据题目中我们发现的信息,这段字符串是12 ...

  6. ios-计算时间方法

    -(NSString *)countPublishTime:(NSString *)sDate { NSDate *dtNow = [NSDate date]; NSDateFormatter *da ...

  7. webbrowser 响应关闭事件

    void registerEvents(System.Windows.Forms.WebBrowser web) { var rnd = new Random(); ]; if (head == nu ...

  8. 剑指offer-在数组中查找两个数,是的他们的和正好是S(一次性跑通)(时间复杂度还可以降低)

    /*对于一个递增的序列,存在2个数字的和相等,要想这2个数字的乘积最小,则这2个数字的距离最远*/ /*思想:j指向最后一个元素,然后i从前扫描看sum-a[j]在这个序列中吗?若不在j--*/ im ...

  9. git配置config文件

    1.Git有一个工具被称为git config,它允许你获取和设置变量:这些变量可以控制Git的外观和操作的各个方面.这些变量以等级的不同可以被存储在三个不同的位置: (1) /etc/gitconf ...

  10. gogs wekan 集成试用

    wekan 官方提供了一个集成gogs 的扩展,不是完全的自动化,需要结合cli,但是官方的cli 写的...(不是很全) 备注: 测试环境使用docker-compose 环境准备 docker-c ...