如何从 Spring Flux 平面图操作中返回对象

Posted

技术标签:

【中文标题】如何从 Spring Flux 平面图操作中返回对象【英文标题】:How to return a object from Spring Flux flatmap operation 【发布时间】:2021-08-03 06:16:56 【问题描述】:

我希望在保存文件后返回 Mono.just(file.getAbsolutePath())。以下是我的代码:

 public Mono<String> save(Mono<FilePart> filePartMono) 
        Mono<String> monoString = filePartMono.flatMap(filePart -> 
            File file = new File(filePart.filename());
            if (file.exists()) 
                file.delete();
                LOG.info("existing file deleted: ", file.getAbsolutePath());
            
            Mono<Void> mono = filePart.transferTo(file);
            LOG.info("file saved: ", file.getAbsolutePath());
            return Mono.just(file.getAbsolutePath());
        ).thenReturn("hello");
        return monoString;

现在我正在返回一个“你好”。有没有办法从我的 save() 方法中返回 file.getAbsolutePath() 而不是字符串?

【问题讨论】:

【参考方案1】:

我认为可以这样:

public Mono<String> save(Mono<FilePart> filePartMono) 
    return filePartMono.flatMap(filePart -> 
        File file = new File(filePart.filename());
        if (file.exists()) 
            file.delete();
            log.info("existing file deleted: ", file.getAbsolutePath());
        
        return filePart.transferTo(file)
            .doOnNext(v -> 
                log.info("file saved: ", file.getAbsolutePath());
            ).thenReturn(file.getAbsolutePath());
    );

【讨论】:

以上是关于如何从 Spring Flux 平面图操作中返回对象的主要内容,如果未能解决你的问题,请参考以下文章