SpringBoot之@Async异步任务
SpringBoot实现异步任务首先要开启异步
@EnableAsync
@SpringBootApplication
public class AsyncdemoApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncdemoApplication.class, args);
}
}
异步任务没有返回值时:
controller代码:
@Controller
public class TestOneController {
@Autowired
private TestOneService testOneService;
@RequestMapping("/hello")
public String getString() {
try {
testOneService.hi();
System.out.println("--------");
System.out.println(Thread.currentThread().getName()+"2");
}
catch (Exception e){
e.printStackTrace();
}
return "error";
}
}
service代码:
@Service
public class TestOneService {
@Async
public void hi() throws InterruptedException {
Thread.sleep(10000);
System.out.println(Thread.currentThread().getName()+"1");
}
}
运行结果:
--------
http-nio-8081-exec-52
task-91
注意,亲测异步任务不能写在controller里面
异步任务有返回值时:
controller代码:
@Controller
public class TestTwoController {
@Autowired
private TestTwoService testTwoService;
@GetMapping("/hello1")
public Map<String, Object> test() throws InterruptedException, ExecutionException {
long start = System.currentTimeMillis();
Map<String, Object> map = new HashMap();
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<String> future = testTwoService.hi(i);
futures.add(future);
}
List<String> response = new ArrayList<>();
for (Future future : futures) {
String string = (String) future.get();
response.add(string);
}
System.out.println(response);
System.out.println("耗时"+(System.currentTimeMillis() - start)+"毫秒" );
return map;
}
}
service代码:
@Service
public class TestTwoService {
@Async
public Future<String> hi(int num) throws InterruptedException {
Thread.sleep(5000);
System.out.println("任务"+num +"执行完成!!");
return new AsyncResult("任务"+num +"执行完成!!");
}
}
运行结果:
5秒时
任务4执行完成!!
任务5执行完成!!
任务6执行完成!!
任务1执行完成!!
任务2执行完成!!
任务0执行完成!!
任务7执行完成!!
10秒时
任务3执行完成!!
任务8执行完成!!
任务9执行完成!!
[任务0执行完成!!, 任务1执行完成!!, 任务2执行完成!!, 任务3执行完成!!, 任务4执行完成!!, 任务5执行完成!!, 任务6执行完成!!, 任务7执行完成!!, 任务8执行完成!!, 任务9执行完成!!]
耗时10002毫秒
结果显示spring自带的异步任务线程数为7个(根据结果推测,不对请指正)