场景
从数据库查询信息,分批查询,50000个查询一次,再把每次查询结果汇总,若是分10次查询,正常查询每次返List<Product>,要等前一次查询返回结果后,才能执行下一次查询,汇总结果,是同步执行的过程。试想若是能够同时进行查询,之间互不影响,每一个查询返回结构后,直接汇总,这样就大大节约了查询时间。 AsyncResult做用就在这里。java
借用举例
AsyncResult是异步方式,异步主要用于调用的代码须要长时间运行,才能返回结果的时候,能够不阻塞调用者。数据库
打个比方,同步方式就是你打电话给客服,客服无法马上解决,客服说你等等,别挂电话,而后等了10分钟,再告诉你。再挂电话。
此时电话费照收,而且你不能接打别人的电话。app
异步方式就是,客服说,我先查查,查到了给你回电话,而后挂断。你干别的事情。等了10分钟,客服给你来电话了,告诉你结果。异步
代码
1,分批查询async
@Override public Integer selectListCount(StorageFeeChargePageCommand command, Integer status,String key) throws Exception { Example example= conditions(command,status); int count = tgStorageFeeChargeMapper.selectCountByExample(example); int rowMaxCount = 50000; //分批查询 int tempsize = (count % rowMaxCount) == 0 ? count / rowMaxCount : count / rowMaxCount + 1; //分页数据对象转换 List<StorageFeeCharge> list = new ArrayList<>(); int listSize =0; ArrayList<Future<List<StorageFeeCharge>>> ret = new ArrayList<Future<List<StorageFeeCharge>>>(); //分批查询 for (int i = 0; i < tempsize; i++) { int pageNum =i+1; Future<List<StorageFeeCharge>> asyncResult1 = storageCommonApplication.asynchronousGetSFeeCharge(pageNum,rowMaxCount,example,key); ret.add(asyncResult1); } int num = 0; //获取返回结果 for (Future<List<StorageFeeCharge>> result : ret){ List<StorageFeeCharge> s = result.get(); listSize += s.size(); s.clear(); } return listSize; }
2,异步查询ide
@Async public Future<List<StorageFeeCharge>> asynchronousGetSFeeCharge(int pageNum, int rowMaxCount, Example example,String key){ //分页数据对象转换 List<StorageFeeCharge> list = new ArrayList<>(); PageWrap<StorageFeeCharge> pageList = new PageWrap<StorageFeeCharge>(); Page<TgStorageFeeCharge> page = PageUtil.startPage(pageNum,rowMaxCount); list = storageCommonRepository.selectPageList( pageNum, rowMaxCount, example); saveRedis(list, key); return new AsyncResult(list); }