标签:attr mes byte span ada todo mon rom 修改
public class ResponseBodyModifyGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return chain.filter(exchange.mutate().response(decorate(exchange)).build()); } ServerHttpResponse decorate(ServerWebExchange exchange) { return new ServerHttpResponseDecorator(exchange.getResponse()) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { Class inClass = String.class; Class outClass = String.class; String originalResponseContentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.CONTENT_TYPE, originalResponseContentType); ClientResponse clientResponse = ClientResponse .create(exchange.getResponse().getStatusCode()) .headers(headers -> headers.putAll(httpHeaders)) .body(Flux.from(body)).build(); Mono modifiedBody = clientResponse.bodyToMono(inClass) .flatMap(originalBody -> { //TODO:此次可以对返回的body进行操作 System.out.println(originalBody + "123"); return Mono.just(originalBody + "123"); }); BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, outClass); CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage( exchange, exchange.getResponse().getHeaders()); return bodyInserter.insert(outputMessage, new BodyInserterContext()) .then(Mono.defer(() -> { Flux<DataBuffer> messageBody = outputMessage.getBody(); HttpHeaders headers = getDelegate().getHeaders(); if (!headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) { messageBody = messageBody.doOnNext(data -> headers .setContentLength(data.readableByteCount())); } return getDelegate().writeWith(messageBody); })); } @Override public Mono<Void> writeAndFlushWith( Publisher<? extends Publisher<? extends DataBuffer>> body) { return writeWith(Flux.from(body).flatMapSequential(p -> p)); } }; } @Override public int getOrder() { return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 10; } }
spring cloud gateway 修改responseBody全局过滤器
标签:attr mes byte span ada todo mon rom 修改
原文地址:https://www.cnblogs.com/zzq-include/p/12957906.html