团队目前在做一个用户数据看板(下面简称看板),基本覆盖用户的所有行为数据,并生成分析报表,用户行为由多个数据来源组成(餐饮、生活日用、充值消费、交通出行、通讯物流、交通出行、医疗保健、住房物业、运动健康...),
基于大量数据的组合、排序和统计。根据最新的统计报告,每天将近100W+的行为数据产生,所以这个数据基数是非常大的。
而这个数据中心,对接很多的业务团队,这些团队根据自己的需要,对某些维度进行筛选,然后直接从我们的中心上下载数据(excel)文档进行分析。所以下个几十万上百万行的数据是很常见的。
目前遇到的主要问题是,随着行为能力逐渐的完善闭环,用户数据沉淀的也越来越多了,同时业务量的也在不断扩大。
业务团队有时候会下载超量的数据来进行分析,平台上的数据下载能力就显得尤为重要了。而我们的问题是下载效率太慢,10W的数据大约要5分钟以上才能下载下来,这显然有问题了。
代码是之前团队遗留的,原先功能没开放使用,没有数据量,所以没有发现问题。以下是原来的导出模块,原程序如下,我做了基本还原。
现在如何保证数据的高效导出是我们最重要的目标,这个也是业务团队最关心的。
1 /**
2 * 获取导出的Excel的文件流信息
3 * @param exportData
4 * @return
5 * @throws Exception
6 */
7 private OutputStream getExportOutPutStream(List exportData) throws Exception {
8 JSONObject object = new JSONObject();
9 List excelCells = new ArrayList<>();
10 String[] headers = new String[] { "A字段","B字段","C字段","D","E","F","G","H","I","J","K","L",
11 "M","N","O","P","Q","R","S","T","U","V","W",
12 "X","Y","Z","AA","AB","AC","AD","AE字段","AF字段","AG字段" };
13 ExcelCell[] headerRow = getHeaderRow(headers);
14 excelCells.add(headerRow);
15 String pattern = "yyyy-MM-dd hh:mm:ss";
16 for (UBehavDto uBehavDto:exportData) {
17 String[] singleRow = new String[] { uBehavDto.getA(),uBehavDto.getB(),uBehavDto.getC(),uBehavDto.getD(),uBehavDto.getE(),uBehavDto.getF(),
18 DateFormatUtils.format(uBehavDto.getAddTime(), pattern),DateFormatUtils.format(uBehavDto.getDate(), pattern),
19 uBehavDto.getG(),uBehavDto.getH(),uBehavDto.getI(),uBehavDto.getJ(),uBehavDto.getK(),uBehavDto.getL(),uBehavDto.getM(),
20 uBehavDto.getN(),uBehavDto.getO(),uBehavDto.getP(),
21 uBehavDto.getQ(),uBehavDto.getR(),uBehavDto.getS(),String.valueOf(uBehavDto.getT()),uBehavDto.getMemo(),uBehavDto.getU(),uBehavDto.getV(),
22 uBehavDto.getW(),uBehavDto.getX(),
23 uBehavDto.getY(),uBehavDto.getZ(),uBehavDto.getAA(),uBehavDto.getAB(),uBehavDto.getAC() };
24 ExcelCell[] cells = new ExcelCell[singleRow.length];
25 ExcelCell getA=new ExcelCell();getA.setValue(uBehavDto.getA());
26 ExcelCell getB=new ExcelCell();getB.setValue(uBehavDto.getB());
27 ExcelCell getC=new ExcelCell();getC.setValue(uBehavDto.getC());
28 ExcelCell getD=new ExcelCell();getD.setValue(uBehavDto.getD());
29 ExcelCell getE=new ExcelCell();getE.setValue(uBehavDto.getE());
30 ExcelCell getF=new ExcelCell();getF.setValue(uBehavDto.getF());
31 ExcelCell getAddTime=new ExcelCell();getAddTime.setValue(DateFormatUtils.format(uBehavDto.getAddTime(), pattern));
32 ExcelCell getDate=new ExcelCell();getDate.setValue(DateFormatUtils.format(uBehavDto.getDate(), pattern));
33 ExcelCell getG=new ExcelCell();getG.setValue(uBehavDto.getG());
34 ExcelCell getH=new ExcelCell();getH.setValue(uBehavDto.getH());
35 ExcelCell getI=new ExcelCell();getI.setValue(uBehavDto.getI());
36 ExcelCell getJ=new ExcelCell();getJ.setValue(uBehavDto.getJ());
37 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getK());
38 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getL());
39 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getM());
40 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getN());
41 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getO());
42 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getP());
43 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getQ());
44 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getR());
45 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getS());
46 ExcelCell a=new ExcelCell();a.setValue(String.valueOf(uBehavDto.getT()));
47 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getMemo());
48 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getU());
49 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getV());
50 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getW());
51 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getX());
52 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getY());
53 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getZ());
54 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getAA());
55 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getAB());
56 ExcelCell a=new ExcelCell();a.setValue(uBehavDto.getAC());
57 ExcelCell[] cells = {
58 new ExcelCell(uBehavDto.getA()),
59 new ExcelCell().setValue(uBehavDto.getB()),
60 new ExcelCell().setValue(uBehavDto.getC()),
61 new ExcelCell().setValue(uBehavDto.getD()),
62 new ExcelCell().setValue(uBehavDto.getE()),
63 new ExcelCell().setValue(uBehavDto.getF()),
64 new ExcelCell().setValue(DateFormatUtils.format(uBehavDto.getAddTime(), pattern)),
65 new ExcelCell().setValue(DateFormatUtils.format(uBehavDto.getDate(), pattern)),
66 new ExcelCell().setValue(uBehavDto.getG()),
67 new ExcelCell().setValue(uBehavDto.getH()),
68 new ExcelCell().setValue(uBehavDto.getI()),
69 new ExcelCell().setValue(uBehavDto.getJ()),
70 new ExcelCell().setValue(uBehavDto.getK()),
71 new ExcelCell().setValue(uBehavDto.getL()),
72 new ExcelCell().setValue(uBehavDto.getM()),
73 new ExcelCell().setValue(uBehavDto.getN()),
74 new ExcelCell().setValue(uBehavDto.getO()),
75 new ExcelCell().setValue(uBehavDto.getP()),
76 new ExcelCell().setValue(uBehavDto.getQ()),
77 new ExcelCell().setValue(uBehavDto.getR()),
78 new ExcelCell().setValue(uBehavDto.getS()),
79 new ExcelCell().setValue(String.valueOf(uBehavDto.getT())),
80 new ExcelCell().setValue(uBehavDto.getMemo()),
81 new ExcelCell().setValue(uBehavDto.getU()),
82 new ExcelCell().setValue(uBehavDto.getV()),
83 new ExcelCell().setValue(uBehavDto.getW()),
84 new ExcelCell().setValue(uBehavDto.getX()),
85 new ExcelCell().setValue(uBehavDto.getY()),
86 new ExcelCell().setValue(uBehavDto.getZ()),
87 new ExcelCell().setValue(uBehavDto.getAA()),
88 new ExcelCell().setValue(uBehavDto.getAB()),
89 new ExcelCell().setValue(uBehavDto.getAC())
90 };
91
92 for(int idx=0;idx
看看标红的代码,这个生成Excel的方式是对Excel中的每一个cell进行渲染,逐行的进行数据填充,效率太慢了,根据日志分析发现:基本时间都耗费在数据生成Excel上。每生成1W左右的数据基本
消耗1分钟的时间。原来在其他业务中他只是作为简量数据导出来使用,比如几百条的数据,很快就出来了,但是遇到大量数据导出的情况,性能问题就立马现形了。
团队内讨论了一下并参考了资料,发现原来业内有很多好用强大的Excel处理组件,我们优先选用阿里的easy excel来做一下尝试。
Pom添加 easyexcel 如下:
com.alibaba
easyexcel
2.1.4
代码:dto内容(中文为配置好的表头):
1 package com.xxx.xxx.modules.worklog.dto;
2
3 import com.alibaba.excel.annotation.ExcelProperty;
4 import lombok.Getter;
5 import lombok.Setter;
6 import java.io.Serializable;
7 import java.util.Date;
8
9 /**
10 * Description:XX表基本信息
11 * Copyright: Copyright (c) 2021
12 * Company: XX Co., Ltd.
13 *
14 * @author brand
15 * @date 2021-06-26 10:07:46
16 * Update Time:
17 * Updater:
18 * Update Comments:
19 */
20 @Setter
21 @Getter
22 public class WorkLogDto implements Serializable {
23 private static final long serialVersionUID = -5523294561640180605L;
24 @ExcelProperty("A字段")
25 private String aClolumn;
26 @ExcelProperty("B字段")
27 private String BColumn;
28 @ExcelProperty("C字段")
29 private String cColumn;
30 @ExcelProperty("D字段")
31 private String dColumn;
32 @ExcelProperty("E字段")
33 private String eColumn;
34 @ExcelProperty("F字段")
35 private String fColumn;
36 @ExcelProperty("G字段")
37 private Date gColumn;
38 @ExcelProperty("H字段")
39 private Date hColumn;
40 @ExcelProperty("I字段")
41 private String iColumn;
42 @ExcelProperty("J字段")
43 private String jColumn;
44 @ExcelProperty("K字段")
45 private String kColumn;
46 @ExcelProperty("L字段")
47 private String lColumn;
48 @ExcelProperty("M字段")
49 private String mColumn;
50 @ExcelProperty("N字段")
51 private String nColumn;
52 @ExcelProperty("O字段")
53 private String oColumn;
54 @ExcelProperty("P字段")
55 private String pColumn;
56 @ExcelProperty("Q字段")
57 private String qColumn;
58 @ExcelProperty("R字段")
59 private String rColumn;
60 @ExcelProperty("S字段")
61 private String sColumn;
62 @ExcelProperty("T字段")
63 private String tColumn;
64 @ExcelProperty("U字段")
65 private String uColumn;
66 @ExcelProperty("V字段")
67 private double vColumn;
68 @ExcelProperty("W字段")
69 private String wColumn;
70 @ExcelProperty("X字段")
71 private String xClumn;
72 @ExcelProperty("Y字段")
73 private String yColumn;
74 @ExcelProperty("Z字段")
75 private String zColumn;
76 }
生成文件流的步骤(代码很清晰了):
1 /**
2 * EasyExcel 生成文件流
3 * @param exportData
4 * @return
5 */
6 private byte[] getEasyExcelOutPutStream(List exportData) {
7 try {
8 WriteCellStyle headWriteCellStyle = new WriteCellStyle();
9 WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
10 contentWriteCellStyle.setWrapped(true);
11 HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
12 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
13 EasyExcel.write(outputStream, WorkLogDto.class).sheet("行为业务数据") // Sheet名称
14 .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
15 .registerWriteHandler(horizontalCellStyleStrategy)
16 .doWrite(exportData);
17 byte[] bytes = outputStream.toByteArray();
18 // 关闭流
19 outputStream.close();
20 return bytes;
21 }
22 catch (Exception ex) {
23 log.error("输出Excel文件流失败:"+ex.getMessage());
24 return null;
25 }
26 }
完整生成Excel文件流并上传:
1 /**
2 * 上传用户数据报表
3 * @param prmWorkLogExport
4 * @param order
5 * @param orderType
6 * @return
7 */
8 @Override
9 @Async
10 public Object uploadWorkLogData(PrmWorkLogExport prmWorkLogExport,ExportTaskDomain domain, String order, String orderType,String suid) {
11 try {
12 log.info(String.format("ExportWorkLog->:%s", "开始获取数据"));
13 List logList = getLogList(prmWorkLogExport,order,orderType);
14 log.info(String.format("ExportWorkLog->:结束获取数据,总 %d 条数据", logList.size()));
15 byte[] bytes = getEasyExcelOutPutStream(logList);
16 log.info(String.format("ExportWorkLog->:%s","完成数据转excel文件流"));
17 /* 暂时作废 Todo
18 int max=55;int min=40;
19 Random random = new Random();
20 int rd = random.nextInt(max)%(max-min+1) + min;
21 modifyExportTask(domain.getId(),0,rd);//计算生成数据的进度
22 */
23 //开始投递文件集群服务器,并将结果反写到数据库
24 log.info(String.format("ExportWorkLog->:%s","开始将数据写入文件服务系统"));
25 Dentry dentry = csService.coverUploadByByteArrayByToken(domain, bytes);
26 //执行异步记录,以免连接池关闭
27 executor.execute(() -> {
28 try {
29 asynworkService.finishExportTask(domain.getId(),domain.getFileName(), dentry);
30 } catch (Exception e) {
31 log.error("更新任务状态失败:", e.getMessage());
32 }
33 });
34
35 } catch (Exception ex) {
36 // 1完成 0进行中 2生产错误
37 String updateSql = String.format(" update exporttask set statu=2 where taskid=%s;",domain.getId());
38 Query query = entityManager.createNativeQuery(updateSql);
39 query.executeUpdate();
40 entityManager.flush();
41 entityManager.clear();
42 log.info(String.format("ExportWorkLog->:上传文件异常:%s",ex.getMessage()));
43 }
44 return null;
45 }
改用阿里 easyexcel 组件后,10W+ 的数据从生成Excel文件流到上传只要8秒,原来约要8分钟 ,以下为各个步骤时间点的日志记录,可以看出时间消耗:
工具类和使用说明
参考网上整理的工具类,有些类、方法在之前的版本是ok的,新版本下被标记为过时了。
1 package com.nd.helenlyn.common.utils;
2
3 import com.alibaba.excel.EasyExcelFactory;
4 import com.alibaba.excel.ExcelWriter;
5 import com.alibaba.excel.context.AnalysisContext;
6 import com.alibaba.excel.event.AnalysisEventListener;
7 import com.alibaba.excel.metadata.BaseRowModel;
8 import com.alibaba.excel.metadata.Sheet;
9 import lombok.Data;
10 import lombok.Getter;
11 import lombok.Setter;
12 import lombok.extern.slf4j.Slf4j;
13 import org.springframework.util.CollectionUtils;
14 import org.springframework.util.StringUtils;
15
16 import java.io.FileInputStream;
17 import java.io.FileNotFoundException;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25
26 /**
27 * @author brand
28 * @Description:
29 * @Copyright: Copyright (c) 2021
30 * @Company: XX, Inc. All Rights Reserved.
31 * @date 2021/7/10 3:54 下午
32 * @Update Time:
33 * @Updater:
34 * @Update Comments:
35 */
36 @Slf4j
37 public class EasyExcelUtil {
38 private static Sheet initSheet;
39 static {
40 initSheet = new Sheet(1, 0);
41 initSheet.setSheetName("sheet");
42 //设置自适应宽度,避免表头重叠情况
43 initSheet.setAutoWidth(Boolean.TRUE);
44 }
45
46 /**
47 * 读取少于1000行数据的情况
48 * @param filePath 文件存放的绝对路径
49 * @return
50 */
51 public static List