S.I*_*L.E 14 java spring spring-boot project-reactor spring-mono
我有以下代码:
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class GreetingHandler
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromValue("Hello Spring!"));
}
}
Run Code Online (Sandbox Code Playgroud)
我理解这段代码,除了 Mono 类做什么以及它的功能是什么。我进行了大量搜索,但并没有直截了当:Mono 类是什么以及何时使用它?
Ale*_*oro 18
AMono<T>是一种特殊的Publisher<T>,最多发出一个项目,然后(可选)以一个onComplete信号或一个onError信号终止。它仅提供可用于 a 的运算符子集Flux,并且一些运算符(特别是将Mono与另一个结合的运算符Publisher)切换到 a Flux。例如,Mono#concatWith(Publisher)返回一个FluxwhileMono#then(Mono)返回另一个Mono。请注意,您可以使用 aMono来表示只有完成概念的无值异步进程(类似于 Runnable)。要创建一个,您可以使用一个空的Mono<Void>.
Mono 和 Flux 都是反应式流。他们表达的内容不同。Mono 是 0 到 1 个元素的流,而 Flux 是 0 到 N 个元素的流。
这两个流的语义差异非常有用,例如向 Http 服务器发出请求期望收到 0 或 1 响应,在这种情况下使用 Flux 是不合适的。相反,在区间上计算数学函数的结果期望区间中的每个数字有一个结果。在另一种情况下,使用 Flux 是合适的。
如何使用它:
Mono.just("Hello World !").subscribe(
successValue -> System.out.println(successValue),
error -> System.error.println(error.getMessage()),
() -> System.out.println("Mono consumed.")
);
// This will display in the console :
// Hello World !
// Mono consumed.
// In case of error, it would have displayed :
// **the error message**
// Mono consumed.
Flux.range(1, 5).subscribe(
successValue -> System.out.println(successValue),
error -> System.error.println(error.getMessage()),
() -> System.out.println("Flux consumed.")
);
// This will display in the console :
// 1
// 2
// 3
// 4
// 5
// Flux consumed.
// Now imagine that when manipulating the values in the Flux, an exception
// is thrown for the value 4.
// The result in the console would be :
// An error as occured
// 1
// 2
// 3
//
// As you can notice, the "Flux consumed." doesn't display because the Flux
// hasn't been fully consumed. This is because the stream stop handling future values
// if an error occurs. Also, the error is handled before the successful values.
Run Code Online (Sandbox Code Playgroud)
来源:Reactor Java #1 - 如何创建 Mono 和 Flux?, Mono, 异步 0-1 结果
它可能会有所帮助:Mono doc
| 归档时间: |
|
| 查看次数: |
16654 次 |
| 最近记录: |