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 avaos.wei
 *  @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 task4() throws InterruptedException {
        calc("task4", 3000);
//        Thread.sleep(1000);
        return new AsyncResult("task 4 finish.");
    }

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

    public Future task6() throws InterruptedException {
        calc("task6", 1000);
//        Thread.sleep(3000);
        return new AsyncResult("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 avaos.wei
 *  @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 task4 = asyncTask.task4();
        Future task5 = asyncTask.task5();
        Future 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

你可能感兴趣的:(spring,boot)