一、获取响应返回信息不全问题: @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { if (!logConfig.isLogOpen()) { return chain.filter(exchange); } GatewayContext gwContext = exchange.getAttribute(GatewayContext.GW_CONTEXT_KEY); ServerHttpResponse response = exchange.getResponse(); DataBufferFactory bufferFactory = response.bufferFactory(); ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { if (body instanceof Flux) { Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body; return super.writeWith(fluxBody.map(dataBuffer -> { byte[] content = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(content); DataBufferUtils.release(dataBuffer); String responseBody = new String(content, StandardCharsets.ISO_8859_1); recordExitAccessLog(gwContext,responseBody); return bufferFactory.wrap(content); })); } return super.writeWith(body); // if body is not a flux. never got there. } }; return chain.filter(exchange.mutate().response(decoratedResponse).build()); }
日志分两次打印
@Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { if (!logConfig.isLogOpen()) { return chain.filter(exchange); } GatewayContext gwContext = exchange.getAttribute(GatewayContext.GW_CONTEXT_KEY); ServerHttpResponse response = exchange.getResponse(); DataBufferFactory bufferFactory = response.bufferFactory(); ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { return super.writeWith(DataBufferUtils.join(Flux.from(body)) .map(dataBuffer -> { byte[] content = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(content); DataBufferUtils.release(dataBuffer); return content; }).flatMap(bytes -> { try{ String responseBody = new String(bytes, StandardCharsets.ISO_8859_1); recordExitAccessLog(gwContext, responseBody); }catch (Exception e){ log.warn("EXIT RECORD ERROR :{}", e.getMessage(), e); MDC.remove("requestId"); } return Mono.just(bufferFactory.wrap(bytes)); })); } @Override public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { return writeWith(Flux.from(body).flatMapSequential(p -> p)); } }; return chain.filter(exchange.mutate().response(decoratedResponse).build()); }