EasyExcel多线程导出并实现Zip压缩

前言:之前实现的需求由于导出时需要的时间过于长,需要优化采用多线程的方式进行导出

更改之后的代码:

首先创建excel的临时文件,并写入。然后创建线程池,调用zipArchiveOutputStream来写入图片和excel

java 复制代码
@PostMapping("/export3")
    public void exportZip(HttpServletResponse response,
                       @RequestParam(value = "startTime",required = false)String startTime,
                       @RequestParam(value = "endTime",required = false)String endTime,
                       @RequestParam(value = "deviceName",required = false)String deviceName) throws IOException {
        List<CutterImageVO> cutterImageVOList = cutterImageService.getCutterImageList(startTime,endTime,deviceName);
        long start = System.currentTimeMillis();
        String zipFileName = "豁口图片数据";
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName + ".zip", "UTF-8"));

        //创建excel临时文件
        final File tempFile = File.createTempFile("tempExcel", ".xls");
        EasyExcel.write(tempFile.getCanonicalPath(),CutterImageVO.class)
                .excelType(ExcelTypeEnum.XLS)
                .registerWriteHandler(new ExcelHyperlinkHandler(1, new int[]{7}))
                .sheet("豁口图片数据")
                .doWrite(cutterImageVOList);
        logger.info("临时文件所在的本地路径:" + tempFile.getCanonicalPath());


        ExecutorService executor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(20), new MyRejectedExecutionHandler());
        ParallelScatterZipCreator parallelScatterZipCreator = new ParallelScatterZipCreator(executor);
        OutputStream outputStream = response.getOutputStream();
        ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputStream);
        zipArchiveOutputStream.setEncoding("UTF-8");

        try {
            for (int i = 0; i <= cutterImageVOList.size(); i++) {
                int finalI = i;
                String fileName = null;
                if (finalI == cutterImageVOList.size()) {
                    fileName = "豁口图片数据.xls";
                } else {
                    fileName = cutterImageVOList.get(i).getImageUrl();
                }
                String finalFileName = fileName;
                final InputStreamSupplier inputStreamSupplier = () -> {
                    try {
                        InputStream inputStream = null;
                        if (finalI == cutterImageVOList.size()) {
                            inputStream = new FileInputStream(tempFile.getCanonicalPath());
                        } else {
                            inputStream = minioUtil.getDownloadInputStream(finalFileName);
                        }
                        return inputStream;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return new NullInputStream(0);
                    }
                };
                ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(fileName);
                zipArchiveEntry.setMethod(ZipArchiveEntry.DEFLATED);
                zipArchiveEntry.setUnixMode(UnixStat.FILE_FLAG | 436);
                parallelScatterZipCreator.addArchiveEntry(zipArchiveEntry, inputStreamSupplier);
            }
            parallelScatterZipCreator.writeTo(zipArchiveOutputStream);
        }catch(Exception e){
            log.error("文件流读取失败",e);
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(zipArchiveOutputStream);
            IOUtils.closeQuietly(outputStream);
        }
        //程序退出时删除临时文件
        tempFile.deleteOnExit();
        long end = System.currentTimeMillis();
        log.info("耗时:"+(end-start));
    }

Minio工具类

java 复制代码
public InputStream getDownloadInputStream(String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
       InputStream is = client.getObject(GetObjectArgs.builder()
               .bucket(minioConfig.getBucketName())
               .object(fileName)
               .build());
       return is;
    }
相关推荐
ascarl20104 分钟前
准确--k8s cgroup问题排查
java·开发语言
magic 2459 分钟前
Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误
java
爱敲代码的憨仔16 分钟前
分布式协同自动化办公系统-工作流引擎-流程设计
java·flowable·oa
纪元A梦40 分钟前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
卿着飞翔42 分钟前
RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)
java·rabbitmq·java-rabbitmq
fpcc1 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
陈阿土i1 小时前
SpringAI 1.0.0 正式版——利用Redis存储会话(ChatMemory)
java·redis·ai·springai
莱茵菜苗1 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长1 小时前
Python 构建法律DeepSeek RAG
开发语言·python
安全系统学习1 小时前
【网络安全】Qt免杀样本分析
java·网络·安全·web安全·系统安全