Spring Boot使用@Async实现异步调用
原文:http://blog.csdn.net/a286352250/article/details/53157822
项目GitHub地址 :
https://github.com/FrameReserve/TrainingBoot
Spring Boot(十)使用@Async实现异步调用 ,标记地址:
https://github.com/FrameReserve/TrainingBoot/releases/tag/0.0.10
Spring Boot启动类,增加@EnableAsync注解配置:
src/main/java/com/training/SpringBootServlet.java
- package com.training;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.builder.SpringApplicationBuilder;
- import org.springframework.boot.web.support.SpringBootServletInitializer;
- import org.springframework.scheduling.annotation.EnableAsync;
- @SpringBootApplication
- @EnableAsync
- public class SpringBootServlet extends SpringBootServletInitializer {
- // jar启动
- public static void main(String[] args) {
- SpringApplication.run(SpringBootServlet.class, args);
- }
- // tomcat war启动
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(SpringBootServlet.class);
- }
- }
测试:
增加异步方法Service,线程休眠:
- package com.training.async.service.impl;
- import java.util.Random;
- import java.util.concurrent.Future;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.scheduling.annotation.AsyncResult;
- import org.springframework.stereotype.Service;
- import com.training.async.service.DemoAsyncService;
- @Service
- public class DemoAsyncServiceImpl implements DemoAsyncService {
- public static Random random =new Random();
- @Async
- public Future<String> doTaskOne() throws Exception {
- System.out.println("开始做任务一");
- long start = System.currentTimeMillis();
- Thread.sleep(random.nextInt(10000));
- long end = System.currentTimeMillis();
- System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
- return new AsyncResult<>("任务一完成");
- }
- @Async
- public Future<String> doTaskTwo() throws Exception {
- System.out.println("开始做任务二");
- long start = System.currentTimeMillis();
- Thread.sleep(random.nextInt(10000));
- long end = System.currentTimeMillis();
- System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
- return new AsyncResult<>("任务二完成");
- }
- @Async
- public Future<String> doTaskThree() throws Exception {
- System.out.println("开始做任务三");
- long start = System.currentTimeMillis();
- Thread.sleep(random.nextInt(10000));
- long end = System.currentTimeMillis();
- System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
- return new AsyncResult<>("任务三完成");
- }
- }
调用异步测试测试,查看控制台输出执行顺序:
- package com.training.async.controller;
- import io.swagger.annotations.ApiOperation;
- import java.util.concurrent.Future;
- import javax.annotation.Resource;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- import com.training.async.service.DemoAsyncService;
- import com.training.core.dto.ResultDataDto;
- @RestController
- @RequestMapping(value="/async")
- public class DemoAsyncController {
- @Resource
- private DemoAsyncService demoAsyncService;
- /**
- * 测试异步方法调用顺序
- */
- @ApiOperation(value="测试异步方法调用顺序", notes="getEntityById")
- @RequestMapping(value = "/getTestDemoAsync", method = RequestMethod.GET)
- public @ResponseBody ResultDataDto getEntityById() throws Exception {
- long start = System.currentTimeMillis();
- Future<String> task1 = demoAsyncService.doTaskOne();
- Future<String> task2 = demoAsyncService.doTaskTwo();
- Future<String> task3 = demoAsyncService.doTaskThree();
- while(true) {
- if(task1.isDone() && task2.isDone() && task3.isDone()) {
- // 三个任务都调用完成,退出循环等待
- break;
- }
- Thread.sleep(1000);
- }
- long end = System.currentTimeMillis();
- System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
- return ResultDataDto.addSuccess();
- }
- }
原文:http://blog.csdn.net/v2sking/article/details/72795742
什么是异步调用?
异步调用是相对于同步调用而言的,同步调用是指程序按预定顺序一步步执行,每一步必须等到上一步执行完后才能执行,异步调用则无需等待上一步程序执行完即可执行。
如何实现异步调用?
多线程,这是很多人第一眼想到的关键词,没错,多线程就是一种实现异步调用的方式。
在非spring目项目中我们要实现异步调用的就是使用多线程方式,可以自己实现Runable接口或者集成Thread类,或者使用jdk1.5以上提供了的Executors线程池。
StrngBoot中则提供了很方便的方式执行异步调用。
按照官方示例开撸
代码入下
maven依赖:
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.3.RELEASE</version>
- </parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- </dependencies>
启动类:添加@EnableAsync注解
- @SpringBootApplication
- @EnableAsync
- public class Application{
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
- }
Controller
只需在需要异步执行方法上添加@Async注解
- @RestController
- @RequestMapping("")
- public class AsyncTaskController {
- @RequestMapping("")
- public String doTask() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- this.task1();
- this.task2();
- this.task3();
- long currentTimeMillis1 = System.currentTimeMillis();
- return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
- }
- @Async
- public void task1() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(1000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- }
- @Async
- public void task2() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(2000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- }
- @Async
- public void task3() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(3000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- }
- }
main函数运行spirngboot项目,启动完成后浏览器访问:
http://localhost:8080/
控制台:
- task1任务耗时:1012ms
- task2任务耗时:2009ms
- task3任务耗时:3004ms
等了一段浏览器时候输出入下:
- task任务总耗时:6002ms
异步并没有执行!
难道是代码写错了?反复检查了好几遍,并没有发现什么明显错误,想起spring对@Transactional注解时也有类似问题,spring扫描时具有@Transactional注解方法的类时,是生成一个代理类,由代理类去开启关闭事务,而在同一个类中,方法调用是在类体内执行的,spring无法截获这个方法调用。
豁然开朗,将异步任务单独放到一个类中,调整代码入下:
Controller
- @RequestMapping("")
- @RestController
- public class AsyncTaskController {
- @Autowired
- private AsyncTask asyncTask;
- @RequestMapping("")
- public String doTask() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- asyncTask.task1();
- asyncTask.task2();
- asyncTask.task3();
- long currentTimeMillis1 = System.currentTimeMillis();
- return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
- }
- }
异步任务类
- @Component
- public class AsyncTask {
- @Async
- public void task1() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(1000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- }
- @Async
- public void task2() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(2000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- }
- @Async
- public void task3() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(3000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- }
- }
控制台:
- task1任务耗时:1012ms
- task2任务耗时:2009ms
- task3任务耗时:3004ms
访问浏览器结果入下:
- task任务总耗时:19ms
异步调用成功!
如何知道三个异步任务什么时候执行完,执行的结果怎样呢?可以采用添加Fature回调方式判断
代码入下:
异步任务类
- @Component
- public class AsyncTask {
- @Async
- public Future<String> task1() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(1000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- return new AsyncResult<String>("task1执行完毕");
- }
- @Async
- public Future<String> task2() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(2000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- return new AsyncResult<String>("task2执行完毕");
- }
- @Async
- public Future<String> task3() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Thread.sleep(3000);
- long currentTimeMillis1 = System.currentTimeMillis();
- System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
- return new AsyncResult<String>("task3执行完毕");
- }
- }
Controller
- @RequestMapping("")
- @RestController
- public class AsyncTaskController {
- @Autowired
- private AsyncTask asyncTask;
- @RequestMapping("")
- public String doTask() throws InterruptedException{
- long currentTimeMillis = System.currentTimeMillis();
- Future<String> task1 = asyncTask.task1();
- Future<String> task2 = asyncTask.task2();
- Future<String> task3 = asyncTask.task3();
- String result = null;
- for (;;) {
- if(task1.isDone() && task2.isDone() && task3.isDone()) {
- // 三个任务都调用完成,退出循环等待
- break;
- }
- Thread.sleep(1000);
- }
- long currentTimeMillis1 = System.currentTimeMillis();
- result = "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
- return result;
- }
- }
控制台输出:
- task1任务耗时:1000ms
- task2任务耗时:2001ms
- task3任务耗时:3001ms
浏览器输出:
- <span style="font-family: Simsun; font-size: 14px;">task任务总耗时:4015ms</span>
异步调用成功,并且在所有任务都完成时程序才返回了结果!
Spring Boot使用@Async实现异步调用的更多相关文章
- Spring Boot使用@Async实现异步调用:自定义线程池
前面的章节中,我们介绍了使用@Async注解来实现异步调用,但是,对于这些异步执行的控制是我们保障自身应用健康的基本技能.本文我们就来学习一下,如果通过自定义线程池的方式来控制异步调用的并发. 定义线 ...
- spring boot中使用@Async实现异步调用任务
本篇文章主要介绍了spring boot中使用@Async实现异步调用任务,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 什么是“异步调用”? “异步调用”对应的是“同步 ...
- spring boot 学习(十一)使用@Async实现异步调用
使用@Async实现异步调用 什么是”异步调用”与”同步调用” “同步调用”就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行:”异步调用”则是只要上一行代码执行,无需等 ...
- Spring Boot -- Spring Boot之@Async异步调用、Mybatis、事务管理等
这一节将在上一节的基础上,继续深入学习Spring Boot相关知识,其中主要包括@Async异步调用,@Value自定义参数.Mybatis.事务管理等. 本节所使用的代码是在上一节项目代码中,继续 ...
- Spring Boot中使用@Async实现异步调用
在Spring Boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数,为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsyn ...
- 56. spring boot中使用@Async实现异步调用【从零开始学Spring Boot】
什么是"异步调用"? "异步调用"对应的是"同步调用",同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执 ...
- Spring Boot中使用@Async实现异步调用,加速任务的执行!
什么是"异步调用"?"异步调用"对应的是"同步调用",同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行 ...
- Spring @Async实现异步调用示例
什么是“异步调用”? “异步调用”对应的是“同步调用”,同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行:异步调用指程序在顺序执行时,不等待异步调用的语句返回结果 ...
- Spring Boot2.0之@Async实现异步调用
补充一个知识点: lombok底层原理使用的是: 字节码技术ASM修改字节码文件,生成比如类似于get() set( )方法 一定要在开发工具安装 在编译时候修改字节码文件(底层使用字节码技术),线上 ...
随机推荐
- 使用state模块部署lamp架构
install_httpd: pkg.installed: - name: httpd httpd_running: service.running: - name: httpd - enable: ...
- bzoj 1576: [Usaco2009 Jan]安全路经Travel——并查集+dijkstra
Description Input * 第一行: 两个空格分开的数, N和M * 第2..M+1行: 三个空格分开的数a_i, b_i,和t_i Output * 第1..N-1行: 第i行包含一个数 ...
- bzoj 2435 BFS
我们可以先将无根树变成有根树,随便选一个点当根就行了,我们选1,bfs求出来每个点 的size值,代表以它为根节点的子树中有多少个节点,(dfs可能会爆栈),然后再对于每一条 边算就好了 我tle了, ...
- 密码字典生成工具crunch的简单使用
案例1: crunch 1 8 #生成最小1位,最大8位,由26个小写字母为元素的所有组合 案例2: crunch 1 6 abcdefg #生成最小为1,最大为6.由abcdefg为元素的所 ...
- 关于chkrootkit 检查 INFECTED: Possible Malicious Linux.Xor.DDoS installed
chkrootkit检测时,发现一个Xor.DDoS内容,内容如下...Searching for Linux.Xor.DDoS ... INFECTED: Possible Malicious Li ...
- [Leetcode Week9]Word Break
Word Break 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-break/description/ Description Given ...
- 解决小米/红米手机无法进行jdwp调试的问题
问题描述:在逆向一个app,研究环境是一台红米2,需要使用jdwp接口,也就是ddms下面这个界面: 但神奇的是,同一台主机上,模拟器的进程可以显示在ddms界面上,红米2确一个进程都没有显示出来.c ...
- K-D树问题 HDU 4347
K-D树可以看看这个博客写的真心不错!这里存个版 http://blog.csdn.net/zhjchengfeng5/article/details/7855241 HDU 4349 #includ ...
- 《JavaScript模式》精要
P25. 如何避免eval()定义全局变量? 如: var jsstring = "var un = 1;"; eval(jsstring); console.log(typeof ...
- HDU 6330.Problem L. Visual Cube-模拟到上天-输出立方体 (2018 Multi-University Training Contest 3 1012)
6330.Problem L. Visual Cube 这个题就是输出立方体.当时写完怎么都不过,后来输出b<c的情况,发现这里写挫了,判断失误.加了点东西就过了,mdzz... 代码: //1 ...