带有Java Reactor的TarArchiveInputStream

问题描述 投票:0回答:1

当前,我正在这样处理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个回答
0
投票

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

How to create a Mono from a completableFuture

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

.flatMap(this::processEmployee).doOnError(this::logError).onErrorResume(getFallbackEmployee())
© www.soinside.com 2019 - 2024. All rights reserved.