一、
1: 启动类里面使用@EnableAsync注解开启功能,自动扫描
2:在要异步任务的类上写@component
3:在定义异步任务类写@Async(写在类上代表整个类都是异步,在方法加上代表该类异步执行)
主类
@SpringBootApplication
@EnableAsync //开启异步任务
@MapperScan("com.qdd.api.mapper.generate")
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// 注意这里要指向原先用main方法执行的Application启动类
return builder.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
异步类
package com.qdd.api.util;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
/**
* 功能描述:异步任务业务类
*/
@Component
@Async
public class AsyncTask {
//获取异步结果
public Future<String> task4() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(2000L);
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(3000L);
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(1000L);
long end = System.currentTimeMillis();
System.out.println("任务6耗时="+(end-begin));
return new AsyncResult<String>("任务6");
}
}
controller类
@Autowired
private AsyncTask task;
/**
*
* 功能描述: 异步任务测试
*
*/
@GetMapping("async_task")
public String exeTask() throws InterruptedException{
long begin = System.currentTimeMillis();
Future<String> task4 = task.task4();
Future<String> task5 = task.task5();
Future<String> task6 = task.task6();
//如果都执行往就可以跳出循环,isDone方法如果此任务完成,true
for(;;){
if (task4.isDone() && task5.isDone() && task6.isDone()) {
break;
}
}
long end = System.currentTimeMillis();
long total = end-begin;
System.out.println("执行总耗时="+total);
return "hello";
}
返回结果
任务6耗时=1000
任务4耗时=2000
任务5耗时=3000
执行总耗时=3020
总结
从上面示例可以看出:如果同步方法,那需要6秒,而异步执行,只需要3秒左右,这就是异步的作用。
1)要把异步任务封装到类里面,不能直接写到Controller
2)增加Future 返回结果 AsyncResult(“task执行完成”);
3)如果需要拿到结果 需要判断全部的 task.isDone()