Java中的Mono类:是什么,何时使用?

Java中的Mono类:是什么,何时使用?,java,spring,spring-boot,project-reactor,spring-mono,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.spri

我有以下代码:

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!"));
    }
}
import org.springframework.http.MediaType;
导入org.springframework.stereotype.Component;
导入org.springframework.web.reactive.function.BodyInserters;
导入org.springframework.web.reactive.function.server.ServerRequest;
导入org.springframework.web.reactive.function.server.ServerResponse;
导入reactor.core.publisher.Mono;
@组成部分
公共类迎宾处理程序
公共Mono hello(服务器请求){
返回ServerResponse.ok().contentType(MediaType.TEXT\u PLAIN)
.body(BodyInserters.fromValue(“Hello Spring!”);
}
}
我理解这段代码,除了Mono类的功能和它的特性。我做了很多搜索,但没有直截了当地说:Mono类是什么,什么时候使用它?

Mono是一个专门的
发行商,它最多发出一个项目,然后(可选地)以
onComplete
信号或
onError
信号终止。 它只提供可用于
流量
的一部分操作符,一些操作符(特别是那些将
单声道
与另一个
发布者
组合的操作符)切换到
流量
。例如,
Mono#concatWith(Publisher)
返回一个
Flux
,而
Mono#然后(Mono)
返回另一个
Mono
。 请注意,您可以使用
Mono
表示只有完成概念的无值异步进程(类似于可运行进程)。要创建一个,可以使用空的
Mono

Mono和Flux都是反应流。他们表达的内容不同。Mono是0到1个元素的流,而Flux是0到N个元素的流

这两个流在语义上的差异非常有用,例如,向Http服务器发出请求期望收到0或1响应,在这种情况下使用流量是不合适的。相反,计算区间上数学函数的结果需要区间中每个数字有一个结果。在另一种情况下,使用助焊剂是合适的

如何使用它:

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.
资料来源:

这可能会有帮助: