1、启动类里面使用@EnableAsync注解开启功能,自动扫描
2.定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async
注意点:
1)要把异步任务封装到类里面,不能直接写到Controller
2)增加Future<String> 返回结果 AsyncResult<String>("task执行完成");
3)如果需要拿到结果 需要判断全部的 task.isDone()
封装的异步任务类
package net.xdclass.redis_project.task;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
@Component
@Async
public class AsyncTask {
public void task1() throws Exception {
Long begin = System.currentTimeMillis();
Thread.sleep(1000L);
Long end = System.currentTimeMillis();
System.out.println("任务1总耗时="+(end-begin));
}
public void task2() throws Exception {
Long begin = System.currentTimeMillis();
Thread.sleep(2000L);
Long end = System.currentTimeMillis();
System.out.println("任务2总耗时="+(end-begin));
}
public void task3() throws Exception {
Long begin = System.currentTimeMillis();
Thread.sleep(3000L);
Long end = System.currentTimeMillis();
System.out.println("任务3总耗时="+(end-begin));
}
//获取异步结果
public Future<String> task4() throws Exception {
Long begin = System.currentTimeMillis();
Thread.sleep(1000L);
Long end = System.currentTimeMillis();
System.out.println("任务3总耗时="+(end-begin));
return new AsyncResult<String>("任务4");
}
//获取异步结果
public Future<String> task5() throws Exception {
Long begin = System.currentTimeMillis();
Thread.sleep(2000L);
Long end = System.currentTimeMillis();
System.out.println("任务3总耗时="+(end-begin));
return new AsyncResult<String>("任务5");
}
//获取异步结果
public Future<String> task6() throws Exception {
Long begin = System.currentTimeMillis();
Thread.sleep(3000L);
Long end = System.currentTimeMillis();
System.out.println("任务3总耗时="+(end-begin));
return new AsyncResult<String>("任务6");
}
}
访问的controller
package net.xdclass.redis_project.controller;
import java.util.concurrent.Future;
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 net.xdclass.redis_project.domain.JsonData;
import net.xdclass.redis_project.task.AsyncTask;
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private AsyncTask task;
@GetMapping("asyncTask")
public JsonData execTask() throws Exception {
Long begin = System.currentTimeMillis();
/*task.task1();
task.task2();
task.task3();*/
Future<String> task4 = task.task4();
Future<String> task5 = task.task5();
Future<String> task6 = task.task6();
for(;;) {
if(task4.isDone()&&task5.isDone()&&task6.isDone()) {
break;
}
}
Long end = System.currentTimeMillis();
Long total = end - begin;
System.out.println("总耗时:"+total);
return JsonData.buildSuccess();
}
}