SpringBoot 异步任务

异步任务

  1. 开启异步任务(在SpringBootApplication类上添加注解)
@EnableAsync
  1. 异步任务
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 *  @title 异步任务-业务类
 *  @Desc
 *  @author <a href="mailto:avaos.wei@gmail.com">avaos.wei</a>
 *  @Date 2020-03-25 16:05
 *
 */
@Slf4j
@Component
@Async
public class AsyncTask {

    public void task1() {
        calc("task1", 1000);
    }

    public void task2() {
        calc("task2", 2000);
    }

    public void task3() {
        calc("task3", 3000);
    }

    public Future<String> task4() throws InterruptedException {
        calc("task4", 3000);
//        Thread.sleep(1000);
        return new AsyncResult<String>("task 4 finish.");
    }

    public Future<String> task5() throws InterruptedException {
        calc("task5", 2000);
//        Thread.sleep(2000);
        return new AsyncResult<String>("task 5 finish.");
    }

    public Future<String> task6() throws InterruptedException {
        calc("task6", 1000);
//        Thread.sleep(3000);
        return new AsyncResult<String>("task 6 finish.");
    }

    private void calc(String msg, long time) {
        long start = System.nanoTime();

        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        log.info("{}: {}", msg, TimeUnit.NANOSECONDS.toMillis(end-start));
    }
}
  1. 使用

import cn.avaos.task.AsyncTask;
import cn.avaos.web.domain.JsonData;
import lombok.extern.slf4j.Slf4j;
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 java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 *  @title 概述
 *  @Desc  描述
 *  @author <a href="mailto:avaos.wei@gmail.com">avaos.wei</a>
 *  @Date 2020-03-25 16:14
 *  
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {


    @Autowired
    private AsyncTask asyncTask;

    @GetMapping(path = "/async_task")
    public JsonData execTask() {

        long start = System.nanoTime();

        asyncTask.task1();

        asyncTask.task2();

        asyncTask.task3();

        long end = System.nanoTime();

        log.info("总耗时:{}", TimeUnit.NANOSECONDS.toMillis(end-start));

        return JsonData.ok();
    }

    @GetMapping(path = "/async_task_result")
    public JsonData execTask2() throws InterruptedException {

        long start = System.nanoTime();

        Future<String> task4 = asyncTask.task4();
        Future<String> task5 = asyncTask.task5();
        Future<String> task6 = asyncTask.task6();

        while(true) {
            if(task4.isDone() && task5.isDone() && task6.isDone())
                break;
        }

        long end = System.nanoTime();

        log.info("总耗时:{}", TimeUnit.NANOSECONDS.toMillis(end-start));

        return JsonData.ok();
    }
}

  1. 注意
  • 要把异步任务封装在类里面,不能直接写在Controller类中
  • 增加Future 返回结果AsyncResult(“任务执行完成”)
  • 如果需要拿到结果,需要判断全部的task.isDone()
  1. 测试
    浏览器访问:
  • GET /api/user/async_task_result
  • GET /api/user/async_task
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一鹿由妳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值