首页 > 解决方案 > 如何让 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();
    }

标签: spring-bootspring-webfluxproject-reactor

解决方案


您的 Web 服务的实现存在几个问题。

何时subscribe

首先,在反应式编程中,您通常必须尝试构建单个处理管道(通过调用MonoandFlux运算符并将最终结果作为 and 返回MonoFlux。在任何情况下,您都应该让框架subscribe在该管道的末尾执行或至少只订阅一次。

相反,您在这里混合了两种方法:您的createDocument方法正确返回 a Mono,但它也返回subscribe. 更糟糕的是,订阅是在中间步骤完成的,在 webservice 方法中没有订阅整个管道。

所以实际上,没有人看到管道的后半部分(以 开头groupBy),因此它永远不会被执行(这是一个惰性的Flux,也称为“冷”通量)。

混合同步和异步

另一个问题再次是混合两种方法的问题:您Flux是惰性的和异步的,但是您的 Web 服务是以命令式和同步的方式编写的。

因此代码从数据库开始异步Flux,立即返回控制器并尝试从磁盘加载文件数据。

选项 1:使控制器更加Flux面向

如果您使用 Spring MVC,您仍然可以编写这些命令式样式的控制器,同时添加一些 WebFlux。在这种情况下,您可以返回一个MonoorFlux并且 Spring MVC 会将其转换为正确的异步 Servlet 构造。但这意味着您必须将OutputStreamandbytes处理转换为, 以使用/ /etc 之类的东西Mono将其链接到文档编写......这有点复杂。MonothenflatMap

选项 2:将其Flux转换为命令式阻塞代码

另一种选择是通过调用block(). createDocument() Mono这将订阅它并等待它完成。之后,您的命令式代码的其余部分应该可以正常工作。

边注

groupBy有一个限制,如果它导致超过256开放组,它可以挂起。在到达文件末尾之前,组无法关闭,但幸运的是,由于您只处理一个月的数据,通量不会超过31组。


推荐阅读