webflux的前置过滤器
public class BusinessRouter extends ForwardedHeaderFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
Flux<DataBuffer> body = request.getBody();
ServerHttpResponse response = exchange.getResponse();
//WebSession session = exchange.getSession().block();
AtomicReference<String> bodyRef = new AtomicReference<>();//缓存读取的request body信息
body.subscribe(dataBuffer -> {
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
DataBufferUtils.release(dataBuffer);
bodyRef.set(charBuffer.toString());
});//读取request body到缓存
String bodyStr = bodyRef.get();//获取request body
Map<String, Object> dataMap = ReqUtil.dataMap(bodyStr);
DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);
request = new ServerHttpRequestDecorator(request){
@Override
public Flux<DataBuffer> getBody() {
return bodyFlux;
}
};//封装我们的request
//继续执行
String a = "1";
if("1".equals(a)){
Map<String, Object> target = new HashMap<>();
Map<String, Object> result = new HashMap<>();
// 状态
Map<String, Object> status = new HashMap<>();
status.put("code", Constants.CODE_USER_NOT_LOGIN);
status.put("message", Constants.MSG_USER_NOT_LOGIN);
target.put("result", result);
target.put("status", status);
return ok().contentType(APPLICATION_JSON_UTF8)
.body(fromPublisher(Mono.just(target), Map.class));
}
return chain.filter(exchange.mutate().request(request).build());
}
}