基于java线程池和EasyExcel实现异步导出

  |   0 评论   |   0 浏览

基于java线程池和EasyExcel实现异步导出

1.controller层

@GetMapping("export")
public void exportExcel(HttpServletResponse response) throws IOException, InterruptedException {
    exportService.exportExcel(response);
}

2. service

public void exportExcel(HttpServletResponse response) throws IOException, InterruptedException {
        //设置响应头
        setExportHeader(response);
        //查询总数
        Long count = salariesMapper.selectCount(null);
        //每页查询条数
        Long pageSize = 40000L;
        //计算总页数
        Long pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        int pages = pageCount.intValue();
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(pages);
        CountDownLatch countDownLatch = new CountDownLatch(pages);

        //根据分页数,使用线程池异步查询数据并封装到Map中,key为页码,value为分页数据
        Map<Integer, Page<Salaries>> pageMap = new HashMap<>();
        for (int i = 0; i < pages; i++) {
            int finalI = i;
            executorService.submit(() -> {
                Page<Salaries> page = new Page<>();
                page.setCurrent(finalI + 1);
                page.setSize(pageSize);
                Page<Salaries> selectPage = salariesMapper.selectPage(page, null);

                pageMap.put(finalI, selectPage);
                //计数器减一
                countDownLatch.countDown();
            });
        }
        //阻塞,等待所有线程执行完(计数器减到0为止)
        countDownLatch.await();
        executorService.shutdown();
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Salaries.class).build()) {
            for (Map.Entry<Integer, Page<Salaries>> entry : pageMap.entrySet()) {
                Integer num = entry.getKey();
                Page<Salaries> salariesPage = entry.getValue();
                WriteSheet writeSheet = EasyExcel.writerSheet(num, "模板" + num).build();
                excelWriter.write(salariesPage.getRecords(), writeSheet);
            }
        }
        // https://github.com/alibaba/easyexcel/issues/1040
    }

标题:基于java线程池和EasyExcel实现异步导出
作者:llp
地址:https://llinp.cn/articles/2025/01/23/1737615258988.html