前言
案例一



案例二



案例三




案例四

案例五




案例六


案例七
@Autowired
private RedissonClient redissonClient;
//原始版本
public BigDecimal getIntervalQty(int itemId, Date startDate, Date endDate) {
String cacheKey = "dashboard:intervalQty:" + itemId + "-" + startDate + "-" + endDate;
RBucket<BigDecimal> bucket = redissonClient.getBucket(cacheKey);
BigDecimal cacheValue = bucket.get();
if (cacheValue != null) {
return cacheValue;
} else {
BigDecimal intervalQty = erpInfoMapper.getIntervalQty(itemId, startDate, endDate);
BigDecimal res = Optional.ofNullable(intervalQty).orElse(BigDecimal.valueOf(0)).setScale(2,
RoundingMode.HALF_UP);
bucket.set(res, 16, TimeUnit.HOURS);
return res;
}
}
//更新避免Redis报错版本
public String getProductLine(String itemNo) {
String cacheKey = "order:getProductLine:" + itemNo;
String cacheValue = null;
RBucket<String> bucket = redissonClient.getBucket(cacheKey);
try {
cacheValue = bucket.get();
} catch (Exception e) {
log.error("redis连接异常", e);
}
if (cacheValue != null) {
return cacheValue;
} else {
String res = ptmErpMapper.getProductLine(itemNo);
bucket.set(res, 16, TimeUnit.HOURS);
return res;
}
}
案例八
通用Controller层
@LimitMethod
@PostMapping("/import")
public RemoteResult<String> importAdd(@RequestParam("file") MultipartFile multipartFile)
1. 第一步生成单号或者标识,userId之类的最好也取出来,做好传递的准备
identifier标识可使用LuaTool生成
String generateOrder = luaTool.generateOrder("SMB-PRODUCT-");
生成局部变量方便线程间数据传递
RequestContext.getCurrentContext()或者使用CurrentUserUtil工具类(sso-zero提供)
2. 第二步调用commonImportExcel方法读取并传递文件到PTM2.0(这一步必须放在外面,是对excel的基本校验,有错误及时推送前端,不能异步)
该方法包含对excel的基本校验,并且自带上传文件服务器以及传递PTM
long ptmFileId = excelTool.commonImportExcel(file, generateOrder);
3. 开启异步,使用readFile或者readMultipartFile解析文件,并进行业务处理
如果此部分需要事务,请另起一个事务类,使用@Transactional(rollbackFor = Exception.class)或者在当前代码区域手动开启事务或者自注入再调用方法。
CompletableFuture.runAsync(() -> {
读取文件,readMultipartFile方法会调用Easy Excel解析读取excel,如果有读取错误会抛出错误,方法入参中有表头校验,选择true会校验表头是否正确,不正确会抛异常
CustomizedExcelListener excelListener = new CustomizedExcelListener();
EasyExcel.read(finalInputStream, MaterialChipImportDTO.class, excelListener).sheet().doRead();
ExcelAnalyzeResDTO analyzeRes = excelListener.getExcelData();
List<MaterialChipImportDTO> judgeMaterialList = (List<MaterialChipImportDTO>) analyzeRes.getExcelDataList();
//业务处理,这里MaterialChipImportDTO导入类需要冗余一个异常信息字段errMsg,业务处理的时候把错误信息塞进去
List<MaterialChipImportDTO> afterList = judgeChipImport(judgeMaterialList, beforeAllList, isAdd);
//判断errMsg字段是否有值,有值说明这一行有业务逻辑错误
MaterialChipImportDTO orElse = judgeMaterialList.stream()
.filter(ma -> StringUtils.isNotBlank(ma.getErrMsg())).findAny().orElse(null);
//可选,异常文件导出
if (orElse != null) {
String fileName = "错误提示文件-" + finalGenerateOrder;
excelTool.synchronizeExportExcel(judgeMaterialList, MaterialChipImportDTO.class, fileName, fileName,userId, userName);
throw new PtmException("文件校验有错误项,请下载错误提示文件");
} else {
//继续业务操作
}
}
})
4. handle处理部分,调用finishFileStatus方法回传PTM2.0状态,注意这里的ptmFileId是指PTM文件列表的id
.handle((res, e) -> {
if (e != null) {
log.error("物料风险地图芯片导入异步处理数据失败,流程单号:{},异常信息:", generateOrder, e);
excelTool.finishFileStatus(ptmFileId, null, null, ExcelFieldConstant.TYPE_IMPORT,
ExcelFieldConstant.IMPORT_FAILED, e.getMessage());
} else {
excelTool.finishFileStatus(ptmFileId, null, null, ExcelFieldConstant.TYPE_IMPORT,ExcelFieldConstant.IMPORT_SUCCESS, null);
}
return null;
});
/**
* @param mFile 上传文件
* @param identifier PTM2.0文件列表查询参数:唯一标识
* @Author WangZY
* @Date 2021/12/14 14:25
* @Description 导入文件--文件下载链接10天有效期
* @return 文件列表ID
**/
public ExcelUploadResDTO commonImportExcel(MultipartFile mFile, String identifier) {
if (mFile.isEmpty()) {
throw new PtmException("上传excel文件不能为空");
} else {
String fileName = mFile.getOriginalFilename();
if (StringUtils.isEmpty(fileName)) {
throw new PtmException("excel名称不能为空");
} else {
if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
throw new PtmException("excel格式不正确");
} else {
//组装Token和文件服务器权限信息发送请求
String token = getToken(true, 10);
if (mFile.getSize() <= 0) {
throw new PtmException("上传文件为空");
} else {
// 先判断文件夹是否存在,避免不存在时报错
String fileDir = commonProperties.getFileDir();
File filePathExist = new File(fileDir);
if (!filePathExist.exists()) {
boolean mkdir = filePathExist.mkdirs();
if (!mkdir) {
return null;
}
}
//将multipartFile转换为临时文件file,避免异步时子线程找不到文件实例
File file = new File(fileDir + mFile.getOriginalFilename());
try (BufferedInputStream bis = new BufferedInputStream(mFile.getInputStream());
BufferedOutputStream bos =
new BufferedOutputStream(Files.newOutputStream(file.toPath()))) {
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
log.error("multipartFileToFile失败", e);
}
String fileId = ExternalApi.uploadFileServer(token, file, splicingFileServerUrl("upload"));
//组装文件信息,在PTM文件列表创建一条处理中的记录
long ptmFileId = createPtmFile(fileId, fileName, identifier, true);
return new ExcelUploadResDTO(ptmFileId, file);
}
}
}
}
}
/**
* @param file 文件
* @param clazz 类
* @Author WangZY
* @Date 2020/12/12 14:24
* @Description 读文件-文件使用后删除
**/
public List<?> readFile(File file, Class<?> clazz, boolean headCheck) {
ExcelListener excelListener = new ExcelListener();
EasyExcel.read(file, clazz, excelListener).sheet().doRead();
ExcelAnalyzeResDTO excelData = excelListener.getExcelData();
if (headCheck) {
checkHeadRight(clazz, excelData);
}
String dateError = excelData.getDateError();
log.info("完成文件解析,删除文件名={},临时文件结果={}", file.getName(), file.delete());
if (!StringUtils.isEmpty(dateError)) {
throw new PtmException(dateError);
} else {
return excelData.getExcelDataList();
}
}
来源|juejin.cn/post/7222676935147651132
后端专属技术群 构建高质量的技术交流社群,欢迎从事编程开发、技术招聘HR进群,也欢迎大家分享自己公司的内推信息,相互帮助,一起进步!
文明发言,以
交流技术
、职位内推
、行业探讨
为主广告人士勿入,切勿轻信私聊,防止被骗
加我好友,拉你进群
原文始发于微信公众号(Java笔记虾):让同事血压飙升的八个 Bug 操作….
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/177712.html