current position:Home>The springcloud gateway takes out the return data response in globalfilter

The springcloud gateway takes out the return data response in globalfilter

2022-01-27 01:40:43 m0_ sixty-four million eight hundred and sixty-seven thousand e

WrapperResponseGlobalFilter.java

import com.alibaba.fastjson.JSONObject;

import com.google.common.base.Joiner;

import com.google.common.base.Throwables;

import com.google.common.collect.Lists;

import org.apache.commons.lang3.StringUtils;

import org.reactivestreams.Publisher;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;

import org.springframework.cloud.gateway.filter.GlobalFilter;

import org.springframework.core.Ordered;

import org.springframework.core.io.buffer.DataBuffer;

import org.springframework.core.io.buffer.DataBufferFactory;

import org.springframework.core.io.buffer.DataBufferUtils;

import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpResponse;

import org.springframework.http.server.reactive.ServerHttpResponseDecorator;

import org.springframework.stereotype.Component;

import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Flux;

import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

import java.util.List;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;

/**

  • @Author JCccc

  • @Description Intercept the returned data , Modify the returned data

  • @Date 2021/8/16 19:22

*/

@Component

public class WrapperResponseGlobalFilter implements GlobalFilter, Ordered {

private static final Logger log = LoggerFactory.getLogger(WrapperResponseGlobalFilter.class);

@Override

public int getOrder() {

// -1 is response write filter, must be called before that

return -2;

}

private static Joiner joiner = Joiner.on("");

@Override

public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {

ServerHttpResponse originalResponse = exchange.getResponse();

DataBufferFactory bufferFactory = originalResponse.bufferFactory();

ServerHttpResponseDecorator response = new ServerHttpResponseDecorator(originalResponse) {

@Override

public Mono writeWith(Publisher<? extends DataBuffer> body) {

if (getStatusCode().equals(HttpStatus.OK) && body instanceof Flux) {

// obtain ContentType, Judge whether to return to JSON Format data

String originalResponseC

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

ontentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);

if (StringUtils.isNotBlank(originalResponseContentType) && originalResponseContentType.contains(“application/json”)) {

Flux<? extends DataBuffer> fluxBody = Flux.from(body);

//( If the string in the returned data is too large , The default is cutting ) Solve the problem of segmented transmission of return body

return super.writeWith(fluxBody.buffer().map(dataBuffers -> {

List list = Lists.newArrayList();

dataBuffers.forEach(dataBuffer -> {

try {

byte[] content = new byte[dataBuffer.readableByteCount()];

dataBuffer.read(content);

DataBufferUtils.release(dataBuffer);

list.add(new String(content, “utf-8”));

} catch (Exception e) {

log.info(“ load Response Byte stream exception , Reasons for failure :{}”, Throwables.getStackTraceAsString(e));

}

});

String responseData = joiner.join(list);

System.out.println(“responseData:”+responseData);

byte[] uppedContent = new String(responseData.getBytes(), Charset.forName(“UTF-8”)).getBytes();

originalResponse.getHeaders().setContentLength(uppedContent.length);

return bufferFactory.wrap(uppedContent);

}));

}

}

return super.writeWith(body);

}

@Override

public Mono writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {

return writeWith(Flux.from(body).flatMapSequential(p -> p));

}

};

return chain.filter(exchange.mutate().response(response).build());

}

}

The calling interface can see ,response The data has been carried out by us :

So let's simply deal with ,

/**

  • Return data processing

  • @param responseData

  • @return

*/

private String responseHandle(String responseData) {

String responseResultJson = null;

copyright notice
author[m0_ sixty-four million eight hundred and sixty-seven thousand e],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270140423673.html

Random recommended