开启异步
@SpringBootApplication
@ServletComponentScan // 配置过滤器 用到
@EnableAsync
public class SpringBootBookV2Application {
// 异步查询
Future<List<AyUser>> findAsynAll();
@Override
@Async
public Future<List<AyUser>> findAsynAll() {
try{
log.info("开始做任务");
long start = System.currentTimeMillis();
List<AyUser> ayUserList = ayUserRepository.findAll();
long end = System.currentTimeMillis();
log.info("完成任务,耗时:" + (end - start) + "毫秒");
return new AsyncResult<List<AyUser>>(ayUserList) ;
}catch (Exception e){
log.error(this.getClass() + "method [findAsynAll()] error",e);
return new AsyncResult<List<AyUser>>(null);
}
}
@Test
public void testAsync2()throws Exception{
long startTime = System.currentTimeMillis();
System.out.println("第一次查询所有用户!");
Future<List<AyUser>> ayUserList = ayUserService.findAsynAll();
System.out.println("第二次查询所有用户!");
Future<List<AyUser>> ayUserList2 = ayUserService.findAsynAll();
System.out.println("第三次查询所有用户!");
Future<List<AyUser>> ayUserList3 = ayUserService.findAsynAll();
while (true){
if(ayUserList.isDone() && ayUserList2.isDone() && ayUserList3.isDone()){
break;
}else {
Thread.sleep(10);
}
}
long endTime = System.currentTimeMillis();
log.info("总共消耗:" + (endTime - startTime) + "毫秒");
}
异步比同步要快 相当于 多线程