【问题标题】:Working with spring webflux reactive repositories results in nested Mono Object使用 spring webflux 响应式存储库会导致嵌套的 Mono 对象
【发布时间】:2021-03-24 01:33:27
【问题描述】:
public interface ApplicationDataRepository extends ReactiveCrudRepository<ApplicationData, Long> {
}

使用 spring webflux 响应式存储库会产生嵌套的 Mono 对象。

applicationDataRepository.findById(100L).map(o -> {
    o.setName("changed name");
    return applicationDataRepository.save(o);
})

以上三行代码结果为Mono&lt;Mono&lt;ApplicationData&gt;&gt;。如何将其转换为 Mono&lt;ApplicationData&gt; 或避免出现这种情况?

【问题讨论】:

  • 该操作不应该是flatMap吗?

标签: java spring spring-webflux reactor


【解决方案1】:

这不是 WebFlux 的问题。它是一个 Reactive Streams 编程模型及其通过 Project Reactor 实现的 API。请先熟悉一下:https://projectreactor.io/

您需要的是MonoflatMap 运算符:

/**
 * Transform the item emitted by this {@link Mono} asynchronously, returning the
 * value emitted by another {@link Mono} (possibly changing the value type).
 *
 * <p>
 * <img class="marble" src="doc-files/marbles/flatMapForMono.svg" alt="">
 *
 * @param transformer the function to dynamically bind a new {@link Mono}
 * @param <R> the result type bound
 *
 * @return a new {@link Mono} with an asynchronously mapped value.
 */
public final <R> Mono<R> flatMap(Function<? super T, ? extends Mono<? extends R>>
        transformer) {

https://projectreactor.io/docs/core/release/reference/#which.values

WebFlux 实际上只是一个 Web:https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#spring-webflux

ReactiveCrudRepository 是 Spring Data 项目的一部分:https://docs.spring.io/spring-data/commons/docs/2.4.6/reference/html/#repositories

我的意思是把所有东西都称为“webflux”是错误的,因为这个主题比 Web 更广泛。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2020-10-08
    • 1970-01-01
    • 2019-02-28
    • 2022-12-17
    • 2020-09-18
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多