基于EasyExcel多线程分页导出excel

基于EasyExcel多线程分页导出excel


第七更,基于EasyExcel 多线程分页导出excel
在项目中,BA要求全量导出表中数据,估计有十几万条,同事使用的是EasyPoi导致内存泄漏,我帮他优化,使用阿里的EasyExcel,解决了内存泄漏问题,但是导出17万数据仍需要84秒(本地测试),于是想到了多线程优化,最终测试时间为40秒,服务器上速度会更快,代码如下

Maven依赖

	<dependencies>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.3</version>
        </dependency>
        
   </dependencies>

线程池配置



import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfig {

    @Bean("excelThreadPool")
    public ExecutorService buildExcelThreadPool() {
        int cpuNum = Runtime.getRuntime().availableProcessors();
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1000);
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("excel-pool-%d").build();
        return new ThreadPoolExecutor(10 * cpuNum, 30 * cpuNum,
                1, TimeUnit.MINUTES, workQueue, threadFactory);
    }
}

导出代码

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MultiThreadExcelExport {

    @Autowired
    @Qualifier("excelThreadPool")
    private ExecutorService executorService;

    @SuppressWarnings("unchecked")
    public void exportExcel() {
        String fileName = "D:\\demo.xlsx";
        ExcelWriter writer = EasyExcel.write(fileName, User.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
        // 根据数据读写速度来调整,一般来说读的逻辑复杂,比较慢,如果读比写快,这里设为1
        int N = 2;
        // 大小设置为2就可以,作为缓冲
        BlockingQueue<List<User>> queue = new ArrayBlockingQueue<>(2);
        AtomicInteger start = new AtomicInteger(0);
        // 分页大小可以适当调整
        int pageSize = 10000;
        //开启多个线程分页查数据
        for (int i = 0; i < N; i++) {
            executorService.submit(() -> {
                while (true) {
                	//自增
                    int startNum= start.getAndAdd(pageSize);
                    try {
                        List<User> list = findPage(startNum, pageSize);
                        if (CollectionUtils.isEmpty(list)) {
                            //读到没数据也要放入空集合
                            queue.put(Collections.EMPTY_LIST);
                            break;
                        }
                        queue.put(list);
                    } catch (Exception e) {
                        //异常情况也要放入空集合,防止写线程无法退出循环
                        queue.put(Collections.EMPTY_LIST);
                        throw new RuntimeException(e);
                    }
                }
            });
        }
        Future<?> submit = executorService.submit(() -> {
         	int count = 0;
            while (true) {
                List<User> list = null;
                try {
                    list = queue.take();
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
                if (CollectionUtils.isEmpty(list)) {
                    count++;
                    // 当获取到两次空集合时,说明已经读完
                    if (count == N) {
                        break;
                    }
                    continue;
                }
                writer.write(list, writeSheet);
            }
            writer.finish();
        });
        try {
            // 阻塞等待完成,异步处理也可以去掉这段代码
            submit.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<User> findPage(int startNum, int pageSize) {
        // todo 实现分页查询
        return new ArrayList<>();
    }

    public static class User {

        private Long id;
        @ExcelProperty("姓名")
        private String name;

        @ExcelProperty("编号")
        private String number;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }
    }

}
  • 7
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
EasyExcel 是一款开源的 Java Excel 操作库,它提供了多线程导出 Excel 的功能。下面是一个简单的示例代码,演示了如何使用 EasyExcel 实现多线程导出 Excel: 首先,确保你已经引入了 EasyExcel 的依赖,可以在 Maven 中添加以下依赖: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.4.0</version> </dependency> ``` 然后,你可以创建一个实现 Runnable 接口的 ExportTask 类,用来导出 Excel: ```java import com.alibaba.excel.EasyExcel; public class ExportTask implements Runnable { private String fileName; public ExportTask(String fileName) { this.fileName = fileName; } @Override public void run() { // 导出 Excel 的逻辑 // 这里只是一个示例,你需要根据自己的需求进行逻辑的编写 EasyExcel.write(fileName, ExportData.class).sheet("Sheet1").doWrite(dataList); } } ``` 在上面的代码中,`ExportData` 是你要导出的数据对象,`dataList` 是导出的数据列表。 接下来,你可以创建一个线程池,并提交多个任务进行导出: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { int threadCount = 5; // 线程数 ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { String fileName = "output_" + i + ".xlsx"; ExportTask exportTask = new ExportTask(fileName); executor.execute(exportTask); } executor.shutdown(); } } ``` 在上面的代码中,`threadCount` 是线程数,根据需求设置合适的值。每个线程都创建一个导出任务,并提交给线程池执行。 这样,就可以实现多线程导出 Excel 文件了。注意在实际使用中,你需要根据自己的数据和业务需求进行适当的修改。希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值