Application
//异步任务 @EnableAsync
异步类
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 {
@Async
public void task1(){
try {
Thread.sleep(4000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task1");
}
@Async
public void task2(){
try {
Thread.sleep(4000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task2");
}
@Async
public Future<String> task3(){
try {
Thread.sleep(4000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task3");
return new AsyncResult<String>("任务三");
}
}
Controller
/**
* 异步任务测试
* 这个的效果类似于用户不需要知道发生了什么,他只要快就可以了,比如说收藏什么的 如果收藏的逻辑写很多
* 虽然不复杂 但是可能耗时 不容易出错 用户根本不需要知道中间发生了什么东西 他只要舒服就好了
* @return
*/
@GetMapping("async")
public JsonData testAsync(){
long begin = System.currentTimeMillis();
asyncTask.task1();
asyncTask.task2();
long end= System.currentTimeMillis();
return JsonData.buildSuccess(end-begin);
}
/**
* 异步任务测试2 这个的效果就相当于 你这个方法里面有很多操作 然后一起并行操作 然后操作完成之后会返回
* 不是很快 但是有返回值给用户
* @return
*/
@GetMapping("async2")
public JsonData testAsync2(){
long begin = System.currentTimeMillis();
Future<String> tesk3 = asyncTask.task3();
for (;;){
if (tesk3.isDone()){
try {
String tesk3Result = tesk3.get();
System.out.println(tesk3Result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
break;
}
}
}
long end= System.currentTimeMillis();
return JsonData.buildSuccess(end-begin);
} 本文作者为DBC,转载请注明。