Spring AOP优化in查询,性能提升巨大
在项目中,经常会出现in查询条件过多,导致慢查询,而分批是我们常见的做法,分批的写法基本是固定的,这意味着我们需要经常写重复的代码,因此,考虑如果能通过AOP+注解实现自动分批,那么对于开发效率会有大大滴提升。
AOP自动分页使用展示
在看具体的代码之前,我们先来看一下,使用AOP实现自动分页后的代码长什么样。
下面是未使用aop进行分页的代码,简单来说,
- 首先会判断spuIds的数量是不是超过一定的阈值,如果没超过的话,就不需要分页直接查询(这个阈值时可以配置的,方便压测的时候随时调整分批大小,这里我用的是美团的lion配置)
- 如果超过阈值后,进行分批,然后使用多线程并行查询(同样的,这里的分批也是可配置的)
- 最终将所有的查询结果返回
public List<SimpleSpuTO> batchQuerySpuDetailByRelationIds(List<Long> spuIds) {if (CollectionUtils.isEmpty(spuIds)) {return Lists.newArrayList();}if (spuIds.size() <= MccUtils.getQuerySpuDetailByRelationIdSize()) {ApiQuerySpuReq apiQuerySpuReq = buildQuerySpuReq(spuIds);return querySpuDetailById(apiQuerySpuReq);}List<SimpleSpuTO> resultList = Lists.newArrayList();//异步分批查询List<Future<List<SimpleSpuTO>>> futures = Lists.newArrayList();List<List<Long>> partition = Lists.partition(spuIds, MccUtils.getQuerySpuDetailByRelationIdSize());for (List<Long> ids : partition) {ApiQuerySpuReq apiQuerySpuReq = buildQuerySpuReq(ids);Future<List<SimpleSpuTO>> future =BATCH_SYNC_QUERY_SPU_POOL.submit(() -> querySpuDetailById(apiQuerySpuReq));futures.add(future);}for (Future<List<SimpleSpuTO>> future : futures) {try {resultList.addAll(future.get());} catch (Exception e) {log.error("batchQuerySpuDetailByRelationIds error", e);}}return resultList;}
接下来看下使用AOP改造后的代码:
@BatchQuery(thresholdLionKey = "querySpuDetailByRelationIdSize", batchSizeLionKey = "querySpuDetailByRelationIdSize", executor = "batchSyncQuerySpuPool")</