在自定义filter里返回值是一个Mono<Void> 如果业务处理发现数据有问题就要返回
这时就有了第一种实现,retrun 一个
Mono.empty();
这种处理办法显然是有问题的,用户根本无从知道他的数据问题在哪。你返回Mono<Void>没有任何意义。只是让fliter停止了而已。
这时就要去查看源码里怎么写的了,我发现了
org.springframework.cloud.gateway.filter.factory.RedirectToGatewayFilterFactory这个类里的一个方法。
它向responseheader里set了Location 然后return 了response.setComplete(); 而这个方法正好返回一个
我们可以使用这个方法实现页面的重定向。
/**
* 失败返回message提示用户
* @param exchange
* @param url
* @return
*/
private Mono<Void> fallBack(String url,ServerWebExchange exchange){
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.SEE_OTHER);
response.getHeaders().set("Location", "你的url");
return exchange.getResponse().setComplete();
}
调用这个方法就可以实现。
2019-11-29更新 上面的方法只能在httpstatus 3xx下返回,如果使用其他返回值 无法带返回结果
private Mono<Void> returnMessage(ServerWebExchange exchange) {
ServerHttpResponse response = exchange.getResponse();
HttpStatus httpStatus = HttpStatus.OK;
String resultStr = "xxxx";
byte[] bits = resultStr.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
response.setStatusCode(httpStatus == null ? HttpStatus.OK : httpStatus);
//指定编码,否则在浏览器中会中文乱码
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
在filter中直接return 即可