SpringBoot异步任务使用方法详解

步骤,如图所示:

1.添加异步任务业务类

package top.ytheng.demo.task;

import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

//异步任务业务类
@Component
//标记此类是异步类,也可在方法中标记
//不加,则类里面的方法为同步执行
@Async
public class AsyncTask {

  public void task1() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(1000);
    long end = System.currentTimeMillis();
    System.out.println("任务1耗时:" + (end - begin));
  }

  public void task2() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(2000);
    long end = System.currentTimeMillis();
    System.out.println("任务2耗时:" + (end - begin));
  }

  public void task3() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(3000);
    long end = System.currentTimeMillis();
    System.out.println("任务3耗时:" + (end - begin));
  }

  //测试拿到返回结果
  public Future<String> task4() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(1000);
    long end = System.currentTimeMillis();
    System.out.println("任务4耗时:" + (end - begin));
    return new AsyncResult<String>("任务4");
  }

  public Future<String> task5() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(2000);
    long end = System.currentTimeMillis();
    System.out.println("任务5耗时:" + (end - begin));
    return new AsyncResult<String>("任务5");
  }

  public Future<String> task6() throws InterruptedException {
    long begin = System.currentTimeMillis();
    Thread.sleep(3000);
    long end = System.currentTimeMillis();
    System.out.println("任务6耗时:" + (end - begin));
    return new AsyncResult<String>("任务6");
  }
}

2.添加测试控制器

package top.ytheng.demo.controller;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import top.ytheng.demo.task.AsyncTask;

@RestController
@RequestMapping("api/v1/async")
public class TaskController {

  @Autowired
  private AsyncTask asyncTask;

  @GetMapping("/test")
  public Object test() throws InterruptedException, ExecutionException {
    long begin = System.currentTimeMillis();
    //asyncTask.task1();
    //asyncTask.task2();
    //asyncTask.task3();
    Future<String> result1 = asyncTask.task4();
    Future<String> result2 = asyncTask.task5();
    Future<String> result3 = asyncTask.task6();
    System.out.println("返回结果:" + result1.get() + "," + result2.get() + "," + result3.get());
    for(;;) {
      if(result1.isDone() && result2.isDone() && result3.isDone()) {
        break;
      }
    }
    long end = System.currentTimeMillis();
    long total = end - begin;
    System.out.println("总耗时:" + total);
    return "总耗时:" + total;
  }
}

3.添加启动类

package top.ytheng.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication //等于下面3个
//@SpringBootConfiguration
//@EnableAutoConfiguration
//@ComponentScan
//拦截器用到
@ServletComponentScan
//MyBatis用到
@MapperScan("top.ytheng.demo.mapper")
//定时使用(开启定时任务)
@EnableScheduling
//开启异步任务
@EnableAsync
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

4.右键项目Run As启动,访问url

http://localhost:8080/api/v1/async/test

结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

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

    什么是"异步调用"? "异步调用"对应的是"同步调用",同步调用指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行:异步调用指程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序.  同步调用 下面通过一个简单示例来直观的理解什么是同步调用: 定义Task类,创建三个处理函数分别模拟三个执行任务的操作,操作消耗时间随机取(10秒内) package com.kfit.task; import java.uti

  • SpringBoot实现定时任务和异步调用

    本文实例为大家分享了SpringBoot实现定时任务和异步调用的具体代码,供大家参考,具体内容如下 环境: jdk1.8:spring boot2.0.2:Maven3.3 摘要说明: 定时任务:定时任务是业务场景中经常出现的一种情况如:定时发送邮件,短信.定时统计监控数据.定时对账等 异步调用:一个都买流程可能包括下单.发货通知.短信推送.消息推送等,其实除了下单这个主要程序是主程序,其他子程序可以同时进行且不影响主程序的运行,这个时候就可以使用异步调用来调用这些子程序: 步骤: 1.定时任务

  • 详解Spring/Spring boot异步任务编程WebAsyncTask

    今天一起学习下如何在Spring中进行异步编程.我们都知道,web服务器处理请求 request 的线程是从线程池中获取的,这也不难解释,因为当web请求并发数非常大时,如何一个请求进来就创建一条处理线程,由于创建线程和线程上下文切换的开销是比较大的,web服务器最终将面临崩溃.另外,web服务器创建的处理线程从头到尾默认是同步执行的,也就是说,假如处理线程A负责处理请求B,那么当B没有 return 之前,处理线程A是不可以脱身去处理别的请求的,这将极大限制了web服务器的并发处理能力. 因此

  • Spring Boot @Async 异步任务执行方法

    1.任务执行和调度 Spring用TaskExecutor和TaskScheduler接口提供了异步执行和调度任务的抽象. Spring的TaskExecutor和java.util.concurrent.Executor接口时一样的,这个接口只有一个方法execute(Runnable task). 1.1.TaskExecutor类型 Spring已经内置了许多TaskExecutor的实现,你没有必要自己去实现: SimpleAsyncTaskExecutor  这种实现不会重用任何线程,

  • spring boot使用自定义配置的线程池执行Async异步任务

    在前面的博客中,http://www.jb51.net/article/106718.htm 我们使用了spring boot的异步操作,当时,我们使用的是默认的线程池,但是,如果我们想根据项目来定制自己的线程池了,下面就来说说,如何定制线程池! 一.增加配置属性类 package com.chhliu.springboot.async.configuration; import org.springframework.boot.context.properties.ConfigurationP

  • spring boot异步(Async)任务调度实现方法

    在没有使用spring boot之前,我们的做法是在配置文件中定义一个任务池,然后将@Async注解的任务丢到任务池中去执行,那么在spring boot中,怎么来实现异步任务的调用了,方法更简单. 我们还是结合前面 spring boot整合JMS(ActiveMQ实现) 这篇博客里面的代码来实现. 一.功能说明 消费者在监听到队列里面的消息时,将接收消息的任务作为异步任务处理. 二.代码修改 消费者1: package com.chhliu.springboot.jms; import or

  • SpringBoot异步任务使用方法详解

    步骤,如图所示: 1.添加异步任务业务类 package top.ytheng.demo.task; import java.util.concurrent.Future; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Compone

  • SpringBoot整合RocketMQ的方法详解

    目录 一:Ubuntu安装RocketMQ 二:添加RocketMQ依赖 三:在application中添加RocketMQ配置 四:编写消费者,消息生产者,消息实体类(自定义) 五:测试Controller 一:Ubuntu安装RocketMQ 1.下载(在下面地址选择自己需要的版本的rocketmq) http://rocketmq.apache.org/release_notes/ 2.解压,更改配置 将下载的zip文件解压到自己需要安装的位置 在unbuntu系统下需要修改安装跟目录下的

  • springBoot整合rabbitMQ的方法详解

    引入pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0

  • SpringBoot整合Shiro的方法详解

    目录 1.Shito简介 1.1 什么是shiro 1.2 有哪些功能 2.QuickStart 3.SpringBoot中集成 1.导入shiro相关依赖 2.自定义UserRealm 3.定义shiroConfig 4.新建页面进行测试 1.Shito简介 1.1 什么是shiro Apache Shiro是一个java安全(权限)框架 Shiro可以非常容易的开发出足够好的应用,其不仅可以用在javase环境,也可以用在javaee环境 shiro可以完成,认证,授权,加密,会话管理,we

  • JavaScript手写异步加法asyncAdd方法详解

    目录 前言 分析 asyncAdd 直观的基本要求 隐藏的考察点 — setTimeout & cb 隐藏的考察点 — async & await 实现 asyncAdd 具体实现 进行优化 抽离内层函数 缓存计算结果 前言 在掘金上发现一道既简单但个人觉得还挺有意思的一道题,题目如下: // 异步加法 function asyncAdd(a,b,cb){ setTimeout(() => { cb(null, a + b) }, Math.random() * 1000) } as

  • SpringBoot热部署设置方法详解

    目录 热部署 手动设置热部署 自动启动热部署 热部署配置范围 属性加载优先级 热部署 手动设置热部署 导入maven坐标 <!--热部署依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> 每次修改点击构建项目 这个还是的手动点击(c

  • SpringBoot yml配置文件读取方法详解

    目录 yaml介绍 yaml语法规则 yaml数据读取 Environment读取yaml全部属性数据 自定义对象封装指定数据 yaml介绍 YAML(YAML Ain't Markup Language),一种数据序列化格式 优点: 容易阅读 容易与脚本语言交互 以数据为核心,重数据轻格式 YANL文件扩展名 .yml(主流) .yaml 几种数据格式比较 yaml语法规则 大小写敏感 属性层级关系使用多行描述,每行结尾使用冒号结束 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许

  • SpringBoot热部署配置方法详解

    目录 前言 手动启动热部署 热部署种类 手动进行热部署 自动启动热部署 热部署范围配置 热部署的关闭 总结 前言 我们在了解一个东西的时候,总是喜欢问的就是为什么要?就是为什么我们需要这个,至少你要告诉我用这个的好处是什么:知道了需求然后学习,效率会好一些. 所以,我们为什么要学习热部署?想象一下这个情况,我们在开发的过程中,每次修改都要重启服务器才能够去重新部署项目,在项目较小的情况下还能忍受,但是如果做的是一个大型项目,部署一次消耗的时间成本很高. 所以热部署的作用 就是为我们免去这些时间上

  • SpringBoot 实现定时任务的方法详解

    一.定时任务实现的几种方式: Timer 这是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务.使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行.一般用的较少. ScheduledExecutorService 也jdk自带的一个类:是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响. Spring Task Spring3.0以后自带的task,可以将它

  • springboot整合solr的方法详解

    这一篇写一下springboot整合solr,代码已经上传到github,传送门. 1.新建core并配置schema solr create -c "book_core" ,配置分词器并且field类型定义为分词器类型. <fieldType name="ik_word" class="solr.TextField"> <analyzer type="index"> <tokenizer cla

随机推荐