使用Spring Webflux返回元素列表

时间:2017-05-30 14:44:49

标签: spring spring-mvc mono flux spring-webflux

我正在尝试使用Spring Webflux创建一个简单的CRUD示例,但我在某些概念中遇到了

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

我在official documentation中找到了一个使用ServerResponse对象的示例:

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

正如您所看到的,即使返回是一个列表(Flux)o ,ServerResponse.ok.body也会创建一个Mono。

所以我的问题:它是这样的吗?换句话说,如果我有一个Flux并不重要,Spring是否总是返回ServerResponse(或其他类似类)的 Mono

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

的内容
.switchIfEmpty(ServerResponse.notFound().build());

但我正在考虑更多流式方式。我可以逐个元素地处理对象列表,例如。

1 个答案:

答案 0 :(得分:1)

我认为您需要功能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))
                ); 
        }
相关问题