使用FeatureTask多线程优化in,提高查询速度
创始人
2024-03-08 12:48:28
0

场景是这样的:使用in查询数据的时候,in的数量越多,效率越低,所以一个优化的思路是,缩小in查询的数量,用多线程的方式查询缩小数量后in的sql,并行查询。

直接上代码:

public List getCscpOrgInfoByUserId(List userIds) {//List list = innerWorkFlowRepository.batchGetCscpOrgInfoByUserId(userIds);List list = getInListThread(userIds);return list;}private List getInListThread(List userIds){List resultList = Collections.synchronizedList(new ArrayList<>());List tasks = new ArrayList<>();int threshold = 3; // 每个线程最大条数int threadNum = userIds.size() / threshold;  // 线程个数int lastSize = userIds.size() % threshold; // 最后一个线程的数据条数//多线程for (int i = 0; i <= threadNum; i++) {int start = i * threshold;int end = 0;if (i != threadNum) {end = (i + 1) * threshold;} else {end = lastSize == 0 ? start : (lastSize + start);}int finalEnd = end;CompletableFuture task = CompletableFuture.runAsync(() -> {List tempMsIdList = new ArrayList<>();for (int j = start; j < finalEnd; j++) {tempMsIdList.add(userIds.get(j));}List temps = new ArrayList<>();if(!org.springframework.util.CollectionUtils.isEmpty(tempMsIdList)){//查询SQLSystem.out.println(Thread.currentThread().getId() + "in的数量:" + tempMsIdList.size());temps =  innerWorkFlowRepository.batchGetCscpOrgInfoByUserId(tempMsIdList);}if (!org.springframework.util.CollectionUtils.isEmpty(temps)) {resultList.addAll(temps);}});tasks.add(task);}CompletableFuture.allOf(tasks.toArray((new CompletableFuture[] {}))).join();return resultList;}

其中,只需配置private的方法中的最大线程数参数threshold即可,按照实际需求配置,此时我配置的参数是3,即每次in的数量是3个,测试userIds的数量是8个。

打印的结果如下(sql日志忽略): 

相关内容

热门资讯

最高检:立足检察公益诉讼职能定... 12月25日,全总召开2025年劳动法律监督“一函两书”典型案例新闻发布会。会上,最高人民检察院公益...
筑牢低空安全根基:无人机法规教... 低空经济作为国家战略性新兴产业,正以技术创新为引擎、应用场景为载体,加快重塑航空产业格局,成为推动经...
规范幼儿园收费 确保普惠政策精... 近日,国家发展改革委、教育部、财政部联合印发《关于完善幼儿园收费政策的通知》,明确幼儿园可收取保育教...
三部门发文:完善幼儿园收费政策 12月23日,由国家发展改革委、教育部、财政部联合印发的《关于完善幼儿园收费政策的通知》(以下简称《...
三部门联合发布2025年劳动法... 中新网12月25日电 据最高人民检察院微信公众号25日消息,中华全国总工会、最高人民法院、最高人民检...
金融领域“黑灰产”违法犯罪集群... 海报新闻记者 孙佃潇 北京报道 12月25日,公安部召开新闻发布会,会上通报公安部和国家金融监督管理...
最高法、全国妇联、司法部联合发... 人民网北京12月25日电 (薄晨棣、高清扬)据最高人民法院消息,24日,最高法与全国妇联、司法部联合...
200余个金融领域犯罪团伙被警... 文 | CFN 大河 图 | 微摄 2025年12月25日,公安部在京召开专题新闻发布会,通报了一场...
锐评丨套牌电动车,闯了法律红灯 一辆在昌平被烧毁的电动车,却在朝阳出现交通违法记录;车牌早已注销,仍收到交通违法提示短信;人在国外度...