由于要导入大量数据,后台会耗费很长时间,导致超时。

本项目前端request.js中设定的超时时间为150s.

const service = axios.create({
baseURL: baseUrl,
withCredentials: true,
timeout: 150000
});

我们的做法是:

前端导入Excel向后台发出请求时,后台立即返回信息“后台正在导入,请稍等!”,向redis中存入键isFinished的值为字符串“0”,并且开启一个线程来完成插入大量数据到数据库的工作,当插入完成则将redis中isFinished的值改为字符串“1”。前端收到“后台正在输入,请稍等!”后,此时导入按钮处于禁用状态并且处于加载状态。通过window.setInterval定时轮询,每隔30秒去后台查询ifFinished值,如果为字符串“1”表示上传完毕,此时在弹框“上传完毕!”,此时导入按钮禁用状态和加载状态都取消,并且刷新列表。

前端代码:

<div style="margin-bottom: 10px">
<el-form :inline="true">
<el-form-item label="">
<el-button type="success" icon="el-icon-download" @click="downloadTemplate">下载模板</el-button>
<el-button :loading="importLoading" type="primary" icon="el-icon-upload" @click="handleImport">导入
</el-button>
<el-upload ref="importUpload" :auto-upload="false" :show-file-list="false" :on-change="handleUploadChange"
:disabled="importDisabled" style="display: inline" action="#" class="upload-demo">
<el-button id="uploadButton" style="display: none" slot="trigger" :loading="importLoading" size="small"
type="primary" icon="el-icon-upload">导入</el-button>
</el-upload>
</el-form-item>
<el-form-item label="">
<el-button type="warning" icon="el-icon-lightning" @click="exportExcel">导出</el-button>
</el-form-item>
</el-form>
</div>

handleUploadChange(file) {
if (file.name.lastIndexOf('.') < 0) {
this.$message.error('上传文件只能是xls、xlsx格式!')
return
}
const testMsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
const extensionXLS = testMsg == 'xls'
const extensionXLSX = testMsg == 'xlsx'
if (!extensionXLS && !extensionXLSX) {
this.$message.error('上传文件只能是xls、xlsx格式!')
return
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('上传文件不能超过 2MB!')
return
}
this.importLoading = true
this.importDisabled = true
const data = new FormData()
data.append('file', file.raw)
medicineListApi.importExcel(data).then(response => {
if (response.status == true) {
this.open2(response.msg)
this.getList()
} else {
this.open2(response.msg)
this.importLoading = false
this.importDisabled = false
}
window.setInterval(() => {
setTimeout(this.getStatus(), 0)
}, 30*1000)
}).catch(() => {
this.open2('抱歉,导入失败')
this.importLoading = false
this.importDisabled = false
})

},
open2(str) {
this.$notify({
title: '提示',
message: str,
duration: 0
})
},
// 请求后台获取是否导入完成的状态
getStatus(){
medicineListApi.getStatus().then(response => {
if (response.data == "1") {
this.open2("上传完毕!")
this.importLoading = false
this.importDisabled = false
this.getList()
}
})
}

项目中我们经常需要实现轮询-每隔几秒请求一次接口刷新数据,一般都会使用setInterval,但要注意单纯使用它会导致页面卡死,解释:setInterval不会清除定时器队列,每重复执行1次都会导致定时器叠加,最终卡死你的网页。但是setTimeout是自带清除定时器的

解决办法:

window.setInterval(() => {
setTimeout(fun, 0)
}, 30000)

setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。 如果你只想重复执行可以使用 setInterval() 方法。setTimeout()只执行一次,而setInterval可以多次调用。

medicineList.js代码:

import request from "./request";

const baseUrl = "/medicineList"
export const medicineListApi = {
/**
* 导入
* @param data
*/
importExcel(data) {
return request({
url: baseUrl + '/import',
method: 'post',
data: data,
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
getStatus() {
return request({
url: baseUrl + "/getStatus",
method: "GET"
});
},
};

后台代码:

controller:

@RestController
@RequestMapping("/medicineList")
@Slf4j
public class MedicineListController extends BaseController { @Autowired
private MedicineListService medicineListService; /**
* 导入药品信息
*
* @param file
* @return
* @throws Exception
*/
@PostMapping("/import")
public JSONObject importNodeInfo(MultipartFile file) throws Exception {
return medicineListService.importNodeInfo(file.getInputStream());
} @GetMapping("/getStatus")
public JSONObject getStatus() {
return medicineListService.getStatus();
}
}

service接口:

public interface MedicineListService extends IService<DrugData> {
JSONObject importNodeInfo(InputStream inputStream) throws Exception; JSONObject getStatus();
}

service实现类:

@Service
public class MedicineListServiceImpl extends ServiceImpl<MedicineListMapper,DrugData> implements MedicineListService { @Resource
private MedicineListMapper medicineListMapper; private static Logger logger = LoggerFactory.getLogger(MedicineListService.class);
@Autowired
private StringRedisTemplate redisTemplate; public JSONObject importNodeInfo(InputStream in) throws Exception {
redisTemplate.opsForValue().set("isFinished","0",60*60l,TimeUnit.SECONDS);
JSONObject json = new JSONObject();
json.put("msg", "后台正在导入,请稍等!");
json.put("status", true);
new Thread() {
@Override
public void run() {
try {
// 根据类型进行分流导入
String str0 = "";
String str = "";
String fstr = "";
int operCount = 0;
XSSFWorkbook workbook = new XSSFWorkbook(in);
XSSFSheet sheet = workbook.getSheetAt(0);
int totalColumnNum = sheet.getRow(0).getLastCellNum();
logger.info("导入代码信息excel文件的总列数:" + totalColumnNum);
System.out.println(totalColumnNum);
int lastRowNum = sheet.getLastRowNum(); logger.info("导入节点信息excel文件的总行数:" + lastRowNum);
System.out.println(sheet.getLastRowNum());
for (int num = 0; num <= lastRowNum; num++) {
XSSFRow row = sheet.getRow(num);
if(row == null) {
str0 = "存在空数据行,行号:" + (num + 1) + ",导入失败!";
break;
}
int hcount = num + 1;
if (num == 0) {
if (null != String.valueOf(row.getCell(0)) && String.valueOf(row.getCell(0)).equals("药品编码")) {
continue;
} else { json.put("msg", "导入的模板名称出错,请确认");
json.put("status", false);
json.put("data", operCount); }
}
DrugData drugData = new DrugData();
String drugNo = String.valueOf(row.getCell(0));
if(StringUtils.isNotBlank(drugNo) && !"null".equalsIgnoreCase(drugNo)) {
drugData.setDrugno(drugNo);// 药品编码
}
String drugName = String.valueOf(row.getCell(1));
if(StringUtils.isNotBlank(drugName) && !"null".equalsIgnoreCase(drugName)) {
drugData.setDrugname(drugName);//药品名称
}
String indiction = String.valueOf(row.getCell(2));
if(StringUtils.isNotBlank(indiction) && !"null".equalsIgnoreCase(indiction)) {
drugData.setIndiction(indiction); //适应症
} try {
QueryWrapper<DrugData> wrapper = new QueryWrapper<>();
if(StringUtils.isNotBlank(drugData.getDrugno())){
wrapper.eq("drugno",drugData.getDrugno());
}
List<DrugData> drugDataList = medicineListMapper.selectList(wrapper); if (null != drugDataList && drugDataList.size() > 0) {
drugData.setId(drugDataList.get(0).getId());
medicineListMapper.updateById(drugData);
} else {
medicineListMapper.insert(drugData);
}
} catch (Exception e) {
logger.error(e.getMessage());
str = str + "第【" + hcount + "】行,";
continue;
}
operCount++;
}
if (StringUtils.isNotBlank(str)) {
str = "其中-->" + str + "导入失败!";
} if (StringUtils.isNotBlank(fstr)) {
fstr = "==投量-->" + fstr + "附表导入失败!";
}
redisTemplate.opsForValue().set("isFinished","1"); json.put("msg", "操作成功" + str0 + str + fstr);
json.put("status", true);
json.put("data", operCount); } catch (Exception e) {
logger.error(e.getMessage());
} finally {
try {
in.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
}.start();
return json;
}
@Override
public JSONObject getStatus() {
String isFinished = redisTemplate.opsForValue().get("isFinished");
JSONObject result = new JSONObject();
if (StringUtils.isNotBlank(isFinished)) {
result.put("msg", "获取成功");
result.put("status", true);
result.put("data",isFinished);
} else {
result.put("msg", "获取失败");
result.put("status", false);
}
redisTemplate.delete("isFinished");
return result;
}
}

注意:导入Excel时,String.valueOf(row.getCell(0))获取的值出了要进行非空判断外,还要判断不为字符串null,再执行插入,否则Excel中未填写的单元格插入数据库会变成字符串null。

解决java POI导入Excel超时问题的更多相关文章

  1. 在java poi导入Excel通用工具类示例详解

    转: 在java poi导入Excel通用工具类示例详解 更新时间:2017年09月10日 14:21:36   作者:daochuwenziyao   我要评论   这篇文章主要给大家介绍了关于在j ...

  2. java poi 导入excel

    最近项目需要导入excel,网上有很多例子,自己整合记录下,兼容2003和2007,暂时没有添加图片处理功能. 所需jar包  http://pan.baidu.com/s/1sjPuWDR pack ...

  3. Java POI导入Excel文件

    今天在公司需要做个导入Excel文件的功能,所以研究了一下,参考网上的一些资料总算是做出来了,在此记录一下防止以后忘记怎么弄. 本人用的是poi3.8,所以需要的JAR包如下: poi-3.8.jar ...

  4. java poi导入Excel(个人代码)

    案例使用的框架:jsp+spring+mybaties <form id="importForm" name="importForm" method=&q ...

  5. java poi导入EXCEL xls文件代码

    /** * */ package com.bn.car.common.report.excel; import java.io.FileInputStream; import java.io.IOEx ...

  6. 解决Java POI 导出Excel时文件名中文乱码,兼容浏览器

    String agent = request.getHeader("USER-AGENT").toLowerCase(); response.setContentType(&quo ...

  7. Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)

    ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...

  8. java如何导入Excel文件

    Java使用POI导入Excel文件,操作起来比较简单,支持xlsx格式. 下载POI资源包 从官网https://poi.apache.org/下载POI,笔者选择的是版本是3.17,下载后文件名是 ...

  9. poi导入Excel,数字科学记数法转换

    在这里分享一下使用poi 导入Excel时 把数字转换为科学记数法的解决方法: 就是使用DecimalFormat对 i 进行了格式化 结果为:

随机推荐

  1. Neo4j 导入 Nebula Graph 的实践总结

    摘要: 主要介绍如何通过官方 ETL 工具 Exchange 将业务线上数据从 Neo4j 直接导入到 Nebula Graph 以及在导入过程中遇到的问题和优化方法. 本文首发于 Nebula 论坛 ...

  2. CENTOS7 使用YUM安装MARIADB

    现在在服务器配置数据库,一般都会直接配置MariaDB,它可以实现mysql数据库连接. 1.安装MariaDB 安装命令 yum -y install mariadb mariadb-server ...

  3. B - B Silver Cow Party (最短路+转置)

    有n个农场,编号1~N,农场里奶牛将去X号农场.这N个农场之间有M条单向路(注意),通过第i条路将需要花费Ti单位时间.选择最短时间的最优路径来回一趟,花费在去的路上和返回农场的这些最优路径的最长时间 ...

  4. ACM 模板库

    Template For ACM 一. 字符串 标准库 sscanf sscanf(const char *__source, const char *__format, ...) :从字符串 __s ...

  5. 【洛谷 p3373】模板-线段树 2(数据结构--线段树)

    题意:已知一个数列,你需要进行下面三种操作:1.将某区间每一个数加上x:2.将某区间每一个数乘上x:3.求出某区间每一个数的和. 解法:(唉 :-(,这题卡住我了......)对于加法和乘法的混合操作 ...

  6. uva10891 Game of Sum(博弈+区间dp+优化)

    题目:点击打开链接 题意:两个人做游戏,共有n个数,每个人可以任选一端取任意多连续的数,问两个人都想拿最多的情况下,先手最多比后手多拿多少分数. 思路:这题一开始想到的是用dp[i][j]表示区间[i ...

  7. HDU-3081-Marriage Match II 二分图匹配+并查集 OR 二分+最大流

    二分+最大流: 1 //题目大意:有编号为1~n的女生和1~n的男生配对 2 // 3 //首先输入m组,a,b表示编号为a的女生没有和编号为b的男生吵过架 4 // 5 //然后输入f组,c,d表示 ...

  8. 牛客编程巅峰赛S1第6场 - 黄金&钻石&王者 A.牛牛爱奇数 (模拟)

    题意:有一组数,每次将所有相等的偶数/2,求最少操作多少次使得所有数变成奇数. 题解:用桶标记,将所有不同的偶数取出来,然后写个while模拟统计一下次数就行. 代码: class Solution ...

  9. 手动编译Selenium源码

    起因 Selenium ChromeDriver和Chrome升级到最新v81版本,同时需要将Selenium3.3.1升级到3.141.59. Selenium本身不支持https,所以修改源码用于 ...

  10. 02、Jmeter正则表达式提取器

    转载自:http://blog.csdn.net/quiet_girl/article/details/50724313 在使用Jmeter过程中,会经常使用到正则表达式提取器提取器,虽然并不直接涉及 ...