SpringBoot整合异步任务以及使用场景

一、SpringBoot异步执行程序

1.在Application上使用注解@EnableAsync开启异步任务

package com.imooc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
//开启异步调用方法
@EnableAsync
public class Application {

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

}

2.在异步类上使用@Componet注解,异步方法上使用@Async注解,作为组件被容器扫描执行

package com.imooc.tasks;

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

import java.util.concurrent.Future;

/**
 * @Description:异步任务类
 */
@Component
public class AsyncTask {

    @Async
    public Future doTask11()throws Exception{
        long start = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时:"+(end-start)+"毫秒");
        return new AsyncResult<>(true);
    }

    @Async
    public Future doTask22()throws Exception{
        long start = System.currentTimeMillis();
        Thread.sleep(700);
        long end = System.currentTimeMillis();
        System.out.println("任务2耗时:"+(end-start)+"毫秒");
        return new AsyncResult<>(true);
    }

    @Async
    public Future doTask33()throws Exception{
        long start = System.currentTimeMillis();
        Thread.sleep(600);
        long end = System.currentTimeMillis();
        System.out.println("任务3耗时:"+(end-start)+"毫秒");
        return new AsyncResult<>(true);
    }

}

3.异步任务测试类

package com.imooc.tasks;

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

import java.util.concurrent.Future;

/**
 * @Description:异步任务测试类
 */
@RestController
@RequestMapping("/tasks")
public class DoTask {

    @Autowired
    private AsyncTask asyncTask;

    @RequestMapping("/test")
    public String test1() throws Exception {
        long start = System.currentTimeMillis();

        Future task1 = asyncTask.doTask11();
        Future task2 = asyncTask.doTask22();
        Future task3 = asyncTask.doTask33();

        while (!task1.isDone() || !task2.isDone() || !task3.isDone()) {
            // 当所有的任务都执行完时,退出
            if (task1.isDone() && task2.isDone() && task3.isDone()) {
                break;
            }
        }
        long end = System.currentTimeMillis();
        String times = "任务全部完成,总耗时:" + (end - start) + "毫秒";
        System.out.println(times);
        return times;
    }
}

4.测试结果:在浏览器中输入:http://localhost:8080/tasks/test。

   总耗时会以最长任务耗时为主,若为同步的话,总好使会远超过1000毫秒。

SpringBoot整合异步任务以及使用场景_第1张图片

SpringBoot整合异步任务以及使用场景_第2张图片

二、SpringBoot异步执行使用场景

1.发送短信

2.发送邮件

3.App消息推送

4.节省运维凌晨发布任务时间,提高效率

 

 

 

你可能感兴趣的:(boot,SpringBoot异步任务,SpringBoot)