WebFlux功能:如何检测空的Flux并返回404? [英] WebFlux functional: How to detect an empty Flux and return 404?

查看:1220
本文介绍了WebFlux功能:如何检测空的Flux并返回404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下简化的处理程序功能(Spring WebFlux和使用Kotlin的功能性API).但是,我需要一个提示,当通量为空时,如何检测空的通量,然后对404使用noContent().

I'm having the following simplified handler function (Spring WebFlux and the functional API using Kotlin). However, I need a hint how to detect an empty Flux and then use noContent() for 404, when the Flux is empty.

fun findByLastname(request: ServerRequest): Mono<ServerResponse> {
    val lastnameOpt = request.queryParam("lastname")
    val customerFlux = if (lastnameOpt.isPresent) {
        service.findByLastname(lastnameOpt.get())
    } else {
        service.findAll()
    }
    // How can I detect an empty Flux and then invoke noContent() ?
    return ok().body(customerFlux, Customer::class.java)
}

推荐答案

来自Mono:

return customerMono
           .flatMap(c -> ok().body(BodyInserters.fromObject(c)))
           .switchIfEmpty(notFound().build());

来自Flux:

return customerFlux
           .collectList()
           .flatMap(l -> {
               if(l.isEmpty()) {
                 return notFound().build();

               }
               else {
                 return ok().body(BodyInserters.fromObject(l)));
               }
           });

请注意,collectList将数据缓存在内存中,因此对于大列表而言,这可能不是最佳选择.也许有更好的方法来解决这个问题.

Note that collectList buffers data in memory, so this might not be the best choice for big lists. There might be a better way to solve this.

这篇关于WebFlux功能:如何检测空的Flux并返回404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆