spring 使用响应实体webflux返回mono对象

0sgqnhkj  于 2022-12-26  发布在  Spring
关注(0)|答案(1)|浏览(372)

我有以下控制器

@RestController
@RequestMapping("/view")
public class ViewController {
@GetMapping(value = "/{channelId}/**")
public Mono<ResponseEntity<ViewResponse>> viewObject(@PathVariable(value = "channelId") String channelId) {

return redisController.getChannelData(channelInfoset, channelId).map(response -> {
     Mono<ViewResponse> processOutput = processViewUrl(channelId); // returns object of Mono.just
    return new ResponseEntity<>(processOutput, responseHeaders, HttpStatus.OK);
}}

返回mono对象的方法

private Mono<ViewResponse> processViewUrl(String channelId){
    return Mono.just(new ViewResponse("val","temp",false));
}

这会导致错误

Incompatible types. Found: 'reactor.core.publisher.Mono<java.lang.Object>', required: 'reactor.core.publisher.Mono<org.springframework.http.ResponseEntity<com.api.model.ViewResponse>>'

这里怎么了?

ioekq8ef

ioekq8ef1#

processOutputMono<ViewResponse>,而不是ViewResponse。要获得Mono<ResponseEntity<ViewResponse>>,您应该将processOutput * Mapa到响应实体:

return redisController.getChannelData(channelInfoset, channelId)
                      .map(response -> {
                          Mono<ViewResponse> processOutput = processViewUrl(channelId);
                         return processOutput.map(value -> new ResponseEntity(value, response.getHeaders(), HttpStatus.OK));
}}

注意,如果processViewUrl方法签名没有约束(API兼容性、潜在的其他异步/复杂实现等),我建议将其更改为直接返回ViewResponse而不是mono。
一般情况下,只有当你想为一个需要发布者作为输入的操作提供一个值时,才需要Mono.just。如果你直接返回一个ViewResponse而不是Mono<ViewResponse>,你的初始代码应该可以工作。

相关问题