Spring Webflux:控制器返回 Mono<ResponseEntity<MyPojo>> 与 Mono<MyPojo>

Pat*_*Pat 8 java spring-webflux

关于我在 Spring Webflux 中看到的返回类型的问题。

在许多示例中,例如在线教程,Spring Webflux 项目的其余 Web 控制器将返回Mono<MyPojo>

    public Mono<MyPojo> monoPojo(String parameter) {
        return WebClient.create("http://...").get().retrieve().bodyToMono(MyPojo.class)
                .map(oneMyPojo -> unregisterRepository.insert(oneMyPojo));
    }
Run Code Online (Sandbox Code Playgroud)

但我也遇到了它返回的项目Mono<ResponseEntity<MyPojo>>

    public Mono<ResponseEntity<MyPojo>> monoResponseEntityPojo(String parameter) {
        return WebClient.create("http://...").get().retrieve().bodyToMono(MyPojo.class)
                .map(oneMyPojo -> unregisterRepository.insert(oneMyPojo))
                .map(ResponseEntity::ok);
    }
Run Code Online (Sandbox Code Playgroud)

Mono<ResponseEntity<MyPojo>>超过有什么好处Mono<MyPojo>

Tho*_*olf 10

让我们澄清一些事情

AResponseEntity<T>来自org.springframework.http包装,而 aServerResponse来自org.springframework.web.reactive.function.server包装。

这应该作为一个开始,应该提示您何时使用什么、在哪里使用。

但简而言之,您可以通过两种方式使用 webflux,或者使用老式@RestController注释,并为每个路径添加注释函数。这是常规 servlet spring web 和 webflux 异步事件驱动编程之间的一种“向后兼容模式”。

ResponseEntities从旧版本返回spring-web,而如果您选择使用 webflux 中存在的功能点,则需要返回ServerResponses

如果您查看这些类的代码,您会发现它们的某些部分相同,但其他部分不同,特别是它们如何存储主体和序列化主体。

Handler functions并且Filter functions在 webflux 中仅适用于ServerResponses.

现在回答你的问题,返回Mono<ResponseEntity<T>Mono<T>

好吧,这一切都取决于你有多懒。

如果您返回一个,Mono<T>框架将尝试找出您在 中拥有什么类型的内容Mono,然后ResponseEntity相应地创建一个。因此,如果您将其序列化为 json,它会为您设置content-type,并将状态通常设置为200 OK

如果您愿意,您可以构建ResponseEntity完全自定义的内容,并返回任何状态代码、任何正文和任何标头等。

所以归根结底就是你有多懒,你希望框架为你做多少事情,你想要明确地做多少事情,然后自己输入所有内容,或者自定义。

我,我很懒,我只是返回一些有用的东西。