Spring Cloud Gateway 修改返回的响应体
问题描述: 在gateway中修改返回的响应体,在全局Filter中添加如下代码:import org.springframework.core.Ordered;import org.springframework.cloud.gateway.filter.GlobalFilter;import org.springframework.cloud.gateway.filter.GatewayFil
·
问题描述: 在gateway中修改返回的响应体,在全局Filter中添加如下代码:
import org.springframework.core.Ordered;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class RequestGlobalFilter implements GlobalFilter, Ordered {
//...
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//...
ResponseDecorator decorator = new ResponseDecorator(exchange.getResponse());
return chain.filter(exchange.mutate().response(decorator).build());
}
@Override
public int getOrder() {
return -1000;
}
}
通过.response(decorator)设置一个响应装饰器(自定义),以下是装饰器具体实现:
import cn.hutool.json.JSONObject;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.Charset;
/**
* @author visy.wang
* @desc 响应装饰器(重构响应体)
*/
public class ResponseDecorator extends ServerHttpResponseDecorator{
public ResponseDecorator(ServerHttpResponse delegate){
super(delegate);
}
@Override
@SuppressWarnings(value = "unchecked")
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
if(body instanceof Flux) {
Flux<DataBuffer> fluxBody = (Flux<DataBuffer>) body;
return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBuffer join = dataBufferFactory.join(dataBuffers);
byte[] content = new byte[join.readableByteCount()];
join.read(content);
DataBufferUtils.release(join);// 释放掉内存
String bodyStr = new String(content, Charset.forName("UTF-8"));
//修改响应体
bodyStr = modifyBody(bodyStr);
getDelegate().getHeaders().setContentLength(bodyStr.getBytes().length);
return bufferFactory().wrap(bodyStr.getBytes());
}));
}
return super.writeWith(body);
}
//重写这个函数即可
private String modifyBody(String jsonStr){
JSONObject json = new JSONObject(jsonStr);
//TODO...修改响应体
return json.toString();
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)