spring-boot - 如何让 Mono 等到依赖 fetch 方法运行
问题描述
我正在尝试通过使用 webflux 的 web 服务实现导出到 excel 功能,因为其他 api 和控制器运行良好。我的问题是调用生成excel文件的函数是在从存储库中检索数据作为 Flux 之后访问的(那里没问题)。我已经对结果进行了排序,并试图通过 flatMap 调用另一个填充方法,我遇到了许多问题,试图让它工作并确保 flatMap 中的代码在 web 服务中的代码返回文件之前运行.
以下是网络服务的代码:
@GetMapping(API_BASE_PATH + "/download")
public ResponseEntity<byte[]> download() {
Mono<Void> createExcel = excelExport.createDocument(false);
Mono.when(createExcel).log("Excel Created").then();
Workbook workbook = excelExport.getWb();
OutputStream outputStream = new ByteArrayOutputStream();
try {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
byte[] media = ((ByteArrayOutputStream) outputStream).toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
headers.setContentType(MediaType.valueOf("text/html"));
headers.set("Content-disposition", "attachment; filename=filename.xlsx");
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK);
return responseEntity;
}
以及 exelExport 类的代码:
public Mono<Void> createDocument(boolean all) {
InputStream inputStream = new ClassPathResource("Timesheet Template.xlsx").getInputStream();
try {
wb = WorkbookFactory.create(inputStream);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(1);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");
log.info("Created document");
Flux<TimeKeepingEntry> entries = service.findByMonth(LocalDate.now().getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH)).log("Excel Export - retrievedMonths");
entries.subscribe();
return entries.groupBy(TimeKeepingEntry::getDateOfMonth).flatMap(Flux::collectList).flatMap(timeKeepingEntries -> this.populateEntry(sheet, timeKeepingEntries)).then();
} catch (IOException e) {
log.error("Error Creating Document", e);
}
//should never get here
return Mono.empty();
}
private void populateEntry(Sheet sheet, List<TimeKeepingEntry> timeKeepingEntries) {
int rowNum = 0;
for (int i = 0; i < timeKeepingEntries.size(); i++) {
TimeKeepingEntry timeKeepingEntry = timeKeepingEntries.get(i);
if (i == 0) {
rowNum = calculateFirstRow(timeKeepingEntry.getDay());
}
LocalDate date = timeKeepingEntry.getFullDate();
Row row2 = sheet.getRow(rowNum);
Cell cell2 = row2.getCell(1);
cell2.setCellValue(date.toString());
if (timeKeepingEntry.getDay().equals(DayOfWeek.FRIDAY.getDisplayName(TextStyle.FULL, Locale.ENGLISH))) {
rowNum = +2;
} else {
rowNum++;
}
}
}
工作簿永远不会更新,因为 populateEntry 永远不会执行。正如我所说,我尝试了许多不同的方法,包括 Mono.just 和 Mono.when,但在 webservice 方法尝试返回文件之前,我似乎无法获得正确的组合来处理它。
任何帮助都会很棒。
Edit1:显示理想的 crateDocument 方法。
public Mono<Void> createDocument(boolean all) {
try {
InputStream inputStream = new ClassPathResource("Timesheet Template.xlsx").getInputStream();
wb = WorkbookFactory.create(inputStream);
Sheet sheet = wb.getSheetAt(0);
log.info("Created document");
if (all) {
//all entries
} else {
service.findByMonth(currentMonthName).log("Excel Export - retrievedMonths").collectSortedList(Comparator.comparing(TimeKeepingEntry::getDateOfMonth)).doOnNext(timeKeepingEntries -> {
this.populateEntry(sheet, timeKeepingEntries);
});
}
} catch (IOException e) {
log.error("Error Importing File", e);
}
return Mono.empty();
}
解决方案
您的 Web 服务的实现存在几个问题。
何时subscribe
首先,在反应式编程中,您通常必须尝试构建单个处理管道(通过调用Mono
andFlux
运算符并将最终结果作为 and 返回Mono
)Flux
。在任何情况下,您都应该让框架subscribe
在该管道的末尾执行或至少只订阅一次。
相反,您在这里混合了两种方法:您的createDocument
方法正确返回 a Mono
,但它也返回subscribe
. 更糟糕的是,订阅是在中间步骤完成的,在 webservice 方法中没有订阅整个管道。
所以实际上,没有人看到管道的后半部分(以 开头groupBy
),因此它永远不会被执行(这是一个惰性的Flux
,也称为“冷”通量)。
混合同步和异步
另一个问题再次是混合两种方法的问题:您Flux
是惰性的和异步的,但是您的 Web 服务是以命令式和同步的方式编写的。
因此代码从数据库开始异步Flux
,立即返回控制器并尝试从磁盘加载文件数据。
选项 1:使控制器更加Flux
面向
如果您使用 Spring MVC,您仍然可以编写这些命令式样式的控制器,同时添加一些 WebFlux。在这种情况下,您可以返回一个Mono
orFlux
并且 Spring MVC 会将其转换为正确的异步 Servlet 构造。但这意味着您必须将OutputStream
andbytes
处理转换为, 以使用/ /etc 之类的东西Mono
将其链接到文档编写......这有点复杂。Mono
then
flatMap
选项 2:将其Flux
转换为命令式阻塞代码
另一种选择是通过调用block()
. createDocument()
Mono
这将订阅它并等待它完成。之后,您的命令式代码的其余部分应该可以正常工作。
边注
groupBy
有一个限制,如果它导致超过256
开放组,它可以挂起。在到达文件末尾之前,组无法关闭,但幸运的是,由于您只处理一个月的数据,通量不会超过31
组。
推荐阅读
- c# - 我可以在 Vue.js 代码中访问 C# 元组值吗?
- c# - ODBC 命令。如何为 LIMIT 操作数传递参数
- c# - 如何对数字和单词进行分组?
- c++ - 是否有一种功能或方法可以删除文件映射的内容而不关闭它?
- javascript - Dojo : TypeError: dojo.byId(...).get is not a function
- wordpress - 如何覆盖自定义分类蛞蝓?
- c# - @Html.DropDownListFor 绑定给出“从类型'System.String'到类型的参数转换”错误
- garbage-collection - java堆中的“活动”对象是什么?(使用 jmap 进行堆转储)
- excel - 使用带有 WScript.Network 的单元格值来提取域数据
- java - 在一种方法中重构大量变量初始化的良好实践