我自定义了个全局过滤器,代码如下,但程序没有进入重写的writeWith,需求就是修改response里的数据
package com.fawvw.ms.pt.cps.sas.isg.filter;
import com.alibaba.fastjson.JSON;
import org.reactivestreams.Publisher;
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.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;
@Component
public class ReBackDataFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return operationExchange(exchange, chain);
}
private Mono<Void> operationExchange(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse response = exchange.getResponse();
System.out.println("@Entry ReBackDataFilter filter response = 【"+ JSON.toJSONString(response) +"】");
DataBufferFactory dataBufferFactory = response.bufferFactory();
ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(response) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
System.out.println("body = " + body);
if (body instanceof Flux) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.map(dataBuffer -> {
// probably should reuse buffers
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String s = new String(content, Charset.forName("UTF-8"));
System.out.println("s = " + s);
//TODO,s就是response的值,想修改、查看就随意而为了
byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
return dataBufferFactory.wrap(uppedContent);
}));
}
return super.writeWith(body);
}
};
return chain.filter(exchange.mutate().response(response).build());
}
@Override
public int getOrder() {
return -2;
}
}