【问题标题】:TarArchiveInputStream with Java Reactor使用 Java Reactor 的 TarArchiveInputStream
【发布时间】:2019-10-10 09:45:39
【问题描述】:

目前我正在处理一个 TarArchiveInputStream:

private Mono<Employee> createEmployeeFromArchiveFile() {

    return Mono.fromCallable(() -> {
        return new Employee();
    })
    .flatMap(employee -> {

        try {
            TarArchiveInputStream tar =
                    new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(new File("/tmp/myarchive.tar.gz"))));
            TarArchiveEntry entry;
            tar.read();
            while ((entry = tar.getNextTarEntry()) != null) {
                if (entry.getName().equals("data1.txt")) {
                    // process data
                    String data1 = IOUtils.toString(tar, String.valueOf(StandardCharsets.UTF_8));
                    if (data1.contains("age")) {
                        employee.setAge(4);
                    } else {
                        return Mono.error(new Exception("Missing age"));
                    }
                }
                if (entry.getName().equals("data2.txt")) {
                    // a lot more processing => put that in another function for clarity purpose
                    String data2 = IOUtils.toString(tar, String.valueOf(StandardCharsets.UTF_8));
                    employee = muchProcessing(employee, data2);
                }
            }
            tar.close();
        } catch (Exception e) {
            return Mono.error(new Exception("Error while streaming archive"));
        }

        return Mono.just(employee);
    });

}

private Employee muchProcessing(Employee employee, String data2) {
    if (data2.contains("name")) {
        employee.setName(4);
    } else {
        // return an error ?
    }
    return employee;
}

首先,这是使用 Reactor 处理存档文件的正确方法吗?它工作正常,但它似乎是 flatMap 中的同步业务。我还没有找到更好的方法。

其次,我不知道如何处理函数muchProcessing(tar)。如果该函数触发错误,它将如何返回它们以便作为 Mono.error 进行适当处理?因为我希望这个函数返回给我一个员工。

谢谢!

【问题讨论】:

    标签: java reactor


    【解决方案1】:

    您可以将flatMap 中的任务作为CompletableFuture 处理,并将其转换为Mono。这是有关如何执行此操作的链接:

    How to create a Mono from a completableFuture

    然后,您可以将其抽象为:

    .flatMap(this::processEmployee).doOnError(this::logError).onErrorResume(getFallbackEmployee())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2019-03-20
      相关资源
      最近更新 更多