大数据批量新增or修改太慢太Low,线程池、CountDownLatch、CompletableFuture完美解决

10 篇文章 0 订阅

需求

上千万数据,分批处理,数据组装后插入到MySQL当中。

痛病

插入效率(耗时极其长)

如何集合分段:

方式1

在这里插入图片描述

方式二

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
        //拆分结合API
List<List<Integer>> partition = Lists.partition(list, 10);

拆分结合工具类:SplitListUtils

需求的解决方案与思路

public class MyCountDownLatch {
    public static final String SONG="---宋先阳";
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 初始化线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        List<Integer> list = new ArrayList<>();
        // 往集合中添加数据
        IntStream.rangeClosed(0,20).forEach(list::add);
        // 集合分段
        List<List<Integer>> lists = SplitListUtils.split(list, 10);
        // 记录单个任务的执行次数
        CountDownLatch downLatch = new CountDownLatch(lists.size());
        // 新增数据的list
        List<String> insertList = Lists.newArrayList();

        for (List<Integer> integerList : lists) {
            // 有返回值的API
            CompletableFuture<List<String>> listCompletableFuture = CompletableFuture.supplyAsync(() ->
                    // 封装处理返回值的方法
                    getStrings(integerList),
                    // 自定义的线程池
                    threadPool
            );
            // 获取线程中结果放入:新增数据的list
            insertList.addAll(listCompletableFuture.get());
            // 任务个数 - 1, 直至为0时唤醒await()
            downLatch.countDown();
            System.out.println("个数::::"+downLatch.getCount());
        }

        // 让当前线程处于阻塞状态,直到锁存器计数为零
        downLatch.await();
        // 批量新增
        if (!CollectionUtils.isEmpty(insertList)) {
            // 执行DAO中的批量新增:
            System.out.println(insertList);
        }

    }

    private static List<String> getStrings(List<Integer> integerList) {
        List<String> childList  = Lists.newArrayList();
        for (Integer integer : integerList) {
            String s=integer+SONG;
            childList.add(s);
        }
        return childList;
    }
}

学习 CountDownLatch、CompletableFuture 搭配使用:MyCountDownLatch

输出结果

在这里插入图片描述

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SteveCode.

永远年轻,永远热泪盈眶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值