[英]How do I conditionally return from a Mono within a WebFilter?
不确定我问的对不对,所以这是我想做的一个例子(以阻塞的命令式风格)
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<MyThing> myThingMono = getMyThingMono();
// I Know this is not right but it's effectively what I want to do
if( myThingMono is empty ) {
return chain.filter(exchange);
} else {
MyThing thing = myThingMono.block(); // I know I can't do this
switch(thing.status) {
case A:
exchange.getResponse().setStatus(HttpStatus.BAD_REQUEST);
return exchange.getResponse().setComplete();
default:
return chain.filter(exchange);
}
}
}
这是我以被动方式获得的最接近的
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<MyThing> myThingMono = getMyThingMono();
myThingMono.map(thing -> {
switch(thing.status) {
case A: return HttpStatus.BAD_REQUEST;
default: return HttpStatus.OK;
}
})
.defaultIfEmpty(HttpStatus.OK) // in case myThingMono is empty
.map(status -> {
switch(status) {
case HttpStatus.OK:
return chain.filter(exchange);
default:
exchange.getResponse().setStatusCode(status);
return exchange.getResponse().setComplete();
}
})
.then();
myThingMono 想要返回 aa Mono<Object>
但我的过滤器期待Mono<Void>
所以我只是将.then()
塞入其中。 我确定这是不对的。
我的代码编译并到达最终的 switch 语句并调用正确的 return 语句,但请求没有到达我的 controller 。 网络过滤器未正确转发请求。 我只是在没有处理程序结果的情况下返回 200 状态。
什么是正确的反应方式来做到这一点?
我的意思是这样的。 如果您的代码在第一次转换中没有输入,我使用.switchIfEmpty(Mono.empty())
返回一些东西。 您还可以创建一个默认Mono.just(new MyThing())
。
然后我使用flatMap
将所有逻辑switch...
放在里面。
enum MyThingEnum { A }
class MyThing { public MyThingEnum status; }
public class Test {
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<MyThing> myThingMono = getMyThingMono();
return myThingMono.flatMap(thing -> {
switch (thing.status) {
case A:
exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
return exchange.getResponse().setComplete();
default:
exchange.getResponse().setStatusCode(HttpStatus.OK);
return chain.filter(exchange);
}
})
.switchIfEmpty(Mono.empty());
}
private Mono<MyThing> getMyThingMono() {
return Mono.just(new MyThing());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.