final Mono<String> bodyMono = authFeignClient.checkToken(headerValue.substring(7), authProperties.getClientId(), authProperties.getClientSecret());
if (bodyMono.block().isEmpty()) {
return returnData(exchange, ResponseWrapper.error(401, "认证未通过"));
} else {
ServerHttpRequest serverHttpRequest = request.mutate().header( "X-CONTEXT-USER", "fdsa").build();
return chain.filter(exchange.mutate().request(serverHttpRequest).build());
}
这种写法是错误的,不能使用 block 。
我试过 authFeignClient.checkToken 返回 String 类型,失败。。。
第二种如上,失败。。。
1
jamel OP 艹,解决了。
final Mono<Void> mono = bodyMono.map(body -> { if (StrUtil.isEmpty(body)) { return returnData(exchange, ResponseWrapper.error(401, "认证未通过")); } ServerHttpRequest serverHttpRequest = request.mutate().header( "X-CONTEXT-USER", "fdsa").build(); return chain.filter(exchange.mutate().request(serverHttpRequest).build()); }).flatMap(it -> it); |
2
ifdef 2022-07-15 11:40:17 +08:00
你没有仔细看 mono 的文档吧,mono 实现了 publisher 接口,是不能直接把 string 赋值给 mono 对象的。
使用 Mono.just(T data)来创造 mono 对象,然后再 subscribe mono 对象 emit 出来的 item. https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html |
3
jamel OP @ifdef 没明白前辈的意思。我的完整代码如下
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); final Mono<String> bodyMono = authFeignClient.checkToken("test", authProperties.getClientId(), authProperties.getClientSecret()); return bodyMono.map(body -> { if (StrUtil.isEmpty(body)) { return returnData(exchange, ResponseWrapper.error(401, "认证未通过")); } ServerHttpRequest serverHttpRequest = request.mutate().header( "X-CONTEXT-USER", "fdasfdas").build(); return chain.filter(exchange.mutate().request(serverHttpRequest).build()); }).flatMap(it -> it); } private Mono<Void> returnData(ServerWebExchange exchange, ResponseWrapper<String> responseWrapper) { ServerHttpResponse response = exchange.getResponse(); DataBuffer buffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(responseWrapper).getBytes()); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); response.setStatusCode(HttpStatus.OK); return response.writeWith(Flux.just(buffer)); } |
4
Real00 2022-07-15 16:29:34 +08:00
注意 bodyMono 可能为空会导致 .map 后续不执行,考虑兜底处理异常或者 XXIfEmpty
|