spring cloud gateway 修改responseBody全局过滤器
Posted soft.push("zzq")
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring cloud gateway 修改responseBody全局过滤器相关的知识,希望对你有一定的参考价值。
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全局过滤器的主要内容,如果未能解决你的问题,请参考以下文章
Spring Cloud Gateway——实现路由动态修改
Spring Cloud Gateway——实现路由动态修改
Spring Cloud Gateway——实现路由动态修改