先看一个@Async的demo
一、demo
1,开启异步任务的开关
在启动类上添加注解@EnableAsync
image.png
2,编写controller类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@RestController
public class TestAsyncController {
@Autowired
private TestAsyncService asyncService;
@RequestMapping(value = "/test/async", method = RequestMethod.GET)
@ResponseBody
public String testAsync() {
long start = System.currentTimeMillis();
Future<String> asyncTaskRes1 = asyncService.asyncTask1();
Future<String> asyncTaskRes2 = asyncService.asyncTask2();
Future<String> asyncTaskRes3 = asyncService.asyncTask3();
String str1 = "";
String str2 = "";
String str3 = "";
try {
str1 = asyncTaskRes1.get();
str2 = asyncTaskRes2.get();
str3 = asyncTaskRes3.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// System.out.println(str1 + str2 + str3);
long end = System.currentTimeMillis();
long time = end - start;
return String.valueOf(time);
}
}
3, service类
@Async注解控制方法是否为异步的
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Service
public class TestAsyncService {
@Async
public Future<String> asyncTask1(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = "asyncTask1";
// 注意返回
return new AsyncResult(value);
}
// @Async
public Future<String> asyncTask2(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = "asyncTask2";
return new AsyncResult(value);
}
// @Async
public Future<String> asyncTask3(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = "asyncTask3";
return new AsyncResult(value);
}
}
结论
本来如果不加@Async,每个方法需要花5秒,一共就是15s; 如果都加上@Async注解就在5-6s的时间(应该有线程调度的消耗)。
网友评论