如何让 Mono 等待 dependentenat fetch 方法运行

D. *_*eer 1 spring-boot project-reactor spring-webflux

我正在尝试通过使用 webflux 的 Web 服务实现导出到 Excel 的功能,因为其他 api 和控制器运行良好。我的问题是,从存储库中检索数据作为 Flux 后,调用生成 excel 文件的函数会被访问(那里没有问题)。我已经对结果进行了排序,并尝试通过 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;
        }

Run Code Online (Sandbox Code Playgroud)

以及 exeelExport 类的代码:


    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++;
                }
            }
        }

Run Code Online (Sandbox Code Playgroud)

工作簿永远不会更新,因为 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();
    }
Run Code Online (Sandbox Code Playgroud)

Sim*_*slé 6

您的网络服务的实施过程中存在几个问题。

何时subscribe

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

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

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

混合同步和异步

另一个问题又是混合两种方法的问题:你的Flux方法是惰性的和异步的,但你的 Web 服务是用命令式和同步的风格编写的。

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

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

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

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

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

边注

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