• 使用FeatureTask多线程优化in,提高查询速度


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

    直接上代码:

    1. public List getCscpOrgInfoByUserId(List userIds) {
    2. //List list = innerWorkFlowRepository.batchGetCscpOrgInfoByUserId(userIds);
    3. List list = getInListThread(userIds);
    4. return list;
    5. }
    6. private List getInListThread(List userIds){
    7. List resultList = Collections.synchronizedList(new ArrayList<>());
    8. List tasks = new ArrayList<>();
    9. int threshold = 3; // 每个线程最大条数
    10. int threadNum = userIds.size() / threshold; // 线程个数
    11. int lastSize = userIds.size() % threshold; // 最后一个线程的数据条数
    12. //多线程
    13. for (int i = 0; i <= threadNum; i++) {
    14. int start = i * threshold;
    15. int end = 0;
    16. if (i != threadNum) {
    17. end = (i + 1) * threshold;
    18. } else {
    19. end = lastSize == 0 ? start : (lastSize + start);
    20. }
    21. int finalEnd = end;
    22. CompletableFuture task = CompletableFuture.runAsync(() -> {
    23. List tempMsIdList = new ArrayList<>();
    24. for (int j = start; j < finalEnd; j++) {
    25. tempMsIdList.add(userIds.get(j));
    26. }
    27. List temps = new ArrayList<>();
    28. if(!org.springframework.util.CollectionUtils.isEmpty(tempMsIdList)){
    29. //查询SQL
    30. System.out.println(Thread.currentThread().getId() + "in的数量:" + tempMsIdList.size());
    31. temps = innerWorkFlowRepository.batchGetCscpOrgInfoByUserId(tempMsIdList);
    32. }
    33. if (!org.springframework.util.CollectionUtils.isEmpty(temps)) {
    34. resultList.addAll(temps);
    35. }
    36. });
    37. tasks.add(task);
    38. }
    39. CompletableFuture.allOf(tasks.toArray((new CompletableFuture[] {}))).join();
    40. return resultList;
    41. }

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

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

  • 相关阅读:
    CH6-中断和异常处理
    SpringBoot官方支持任务调度框架,轻量级用起来也挺香!
    hive安装和shell交互全步骤
    C# ref用法,实现引用传递(地址传递)
    更改搜索路径上的文件夹
    Java基础
    C++ 外观模式的实现
    探索科技地图:通向未来的科技之路
    SpringBoot系列之搭建WebSocket应用
    docker将Java、vue、nginx打进镜像(涉及容器打成镜像)
  • 原文地址:https://blog.csdn.net/Pastthewind/article/details/128137267