使用Spring Webflux返回元素列表

Igo*_*oso 5 mono spring spring-mvc flux spring-webflux

我正在尝试使用Spring Webflux创建一个CRUD的简单示例,但是我陷入了一些概念中。

我知道我可以在控制器请求映射方法中返回Flux。但是有时候我想返回404状态,所以我可以以某种方式处理前端。

我在官方文档中找到了一个使用ServerResponse对象的示例:

        public Mono<ServerResponse> listPeople(ServerRequest request) { 
                Flux<Person> people = repository.allPeople();
                return ServerResponse.ok().contentType(APPLICATION_JSON).body(people, Person.class);
        }
Run Code Online (Sandbox Code Playgroud)

如您所见,即使返回是一个列表(Flux)或person,ServerResponse.ok.body也会创建一个Mono。

所以我的问题是:是这样吗?换句话说,如果我有Flux没关系,Spring是否总是返回Mono的ServerResponse(或其他类似的类)?

对于我的404状态,我可以使用类似

.switchIfEmpty(ServerResponse.notFound().build());
Run Code Online (Sandbox Code Playgroud)

但是我在想更多的流媒体方式。例如,我可以逐个元素地处理对象列表。

小智 3

我认为你需要函数collectList()flatMap()。像这样:

public Mono<ServerResponse> listPeople(ServerRequest request) { 
                Flux<Person> people = repository.allPeople();
                return people.collectList().flatMap(p->
                    p.size() < 1 ?
                        ServerResponse.status(404).build()
                       :ServerResponse.ok().contentType(APPLICATION_JSON).body(fromObject(p))
                ); 
        }
Run Code Online (Sandbox Code Playgroud)