异步任务的使用场景及好处
使用场景:1.发送邮件 2.消息推送 3.执行计划任务(与消息队列)
好处:提高效率
异步任务的简单配置
1.在SpringBootApplication启动类中增加注解 @EnableAsync开启定时任务,项目启动会自动进行扫描
2.在任务类中增加注解 @Component 及 @Async 被容器扫描 (注意:不加注解@Async为同步任务)
实例
定义异步任务 其中定义完成2个方法
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
@Async
public Future<Boolean> doTask1() 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<Boolean> doTask2() throws Exception {
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("任务2耗时:" + (end - start) + "毫秒");
return new AsyncResult<>(true);
}
}
测试方法
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("tasks")
public class DoTask {
@Autowired
private AsyncTask asyncTask;
@RequestMapping("taskTest")
public String taskTest() throws Exception {
long start = System.currentTimeMillis();
Future<Boolean> a = asyncTask.doTask1();
Future<Boolean> b = asyncTask.doTask2();
//判断只要有任务没有完成 必须要执行这个方法
//当所有任务执行完成之后 才可以break
while (!a.isDone() || !b.isDone() ) {
if (a.isDone() && b.isDone() ) {
break;
}
}
long end = System.currentTimeMillis();
String times = "任务全部完成,总耗时:" + (end - start) + "毫秒";
System.out.println(times);
return times;
}
}
任务结果
为什么不是1000 因为我们方法中有一个循环操作 会有一个时间的消耗