Spring Cloud Gateway 3 全局过滤器中修改响应体案例 1
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
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.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class ModifyResponseBodyGlobalFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse originalResponse = exchange.getResponse();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
private boolean bodyWritten = false;
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
if (body instanceof Flux) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.map(dataBuffer -> {
// 这里可以对响应体进行修改操作
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
DataBufferUtils.release(dataBuffer);
// 修改content内容
// ...
// 将修改后的内容重新封装成DataBuffer
// ...
return bufferFactory.wrap(modifiedContent);
}));
}
// 否则,直接返回原有响应体
return super.writeWith(body);
}
};
// 将修饰后的ServerHttpResponse替换到exchange中
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
}
这段代码展示了如何在Spring Cloud Gateway的全局过滤器中修改响应体。它首先定义了一个\`ModifyRespon
评论已关闭