使用 spring webflux 反应性存储库会产生嵌套的 Mono 对象
Working with spring webflux reactive repositories results in nested Mono Object
public interface ApplicationDataRepository extends ReactiveCrudRepository<ApplicationData, Long> {
}
使用 spring webflux 反应性存储库会产生嵌套的 Mono 对象。
applicationDataRepository.findById(100L).map(o -> {
o.setName("changed name");
return applicationDataRepository.save(o);
})
以上三行代码的结果是Mono<Mono<ApplicationData>>
。我怎样才能将其转换为 Mono<ApplicationData>
或避免出现这种情况?
这不是 WebFlux 的问题。它是一个 Reactive Streams 编程模型及其 API 通过 Project Reactor 实现。请先熟悉一下:https://projectreactor.io/
您需要的是 Mono
:
的 flatMap
运算符
/**
* 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 数据项目的一部分:https://docs.spring.io/spring-data/commons/docs/2.4.6/reference/html/#repositories
我的意思是,将所有内容都称为“webflux”是错误的,因为该主题比 Web 更广泛。
public interface ApplicationDataRepository extends ReactiveCrudRepository<ApplicationData, Long> {
}
使用 spring webflux 反应性存储库会产生嵌套的 Mono 对象。
applicationDataRepository.findById(100L).map(o -> {
o.setName("changed name");
return applicationDataRepository.save(o);
})
以上三行代码的结果是Mono<Mono<ApplicationData>>
。我怎样才能将其转换为 Mono<ApplicationData>
或避免出现这种情况?
这不是 WebFlux 的问题。它是一个 Reactive Streams 编程模型及其 API 通过 Project Reactor 实现。请先熟悉一下:https://projectreactor.io/
您需要的是 Mono
:
flatMap
运算符
/**
* 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 数据项目的一部分:https://docs.spring.io/spring-data/commons/docs/2.4.6/reference/html/#repositories
我的意思是,将所有内容都称为“webflux”是错误的,因为该主题比 Web 更广泛。