Spring Gateway 对请求体和响应体进行修改
大约 1 分钟
Spring Gateway 对请求体和响应体进行修改
请求体修改
使用 GlobalFilter 过滤所有请求,用 ModifyRequestBodyGatewayFilterFactory 生成的 filter 通过 RewriteFunction 修改请求体。
源码
@Component
@Order(10)
public class RequestBodyModifyFilter implements GlobalFilter{
@Resource
private ModifyRequestBodyGatewayFilterFactory modifyRequestBodyGatewayFilterFactory;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return reqBodyRewriter().filter(exchange, chain);
}
/**
* 修改请求体的filter
*/
@Bean
private GatewayFilter reqBodyRewriter(){
return modifyRequestBodyGatewayFilterFactory.apply(new ModifyRequestBodyGatewayFilterFactory.Config().setRewriteFunction(
String.class, String.class, rewriteFunction()
));
}
/**
* 此处是对原请求体的修改方法
*/
private RewriteFunction<String, String> rewriteFunction(){
return (serverWebExchange, s) -> {
//对请求体进行操作、s为原请求体
return Mono.just("修改后的结果");
};
}
}
响应体修改
同上,通过 RewriteFunction 修改请求体。
源码
@Component
public class SM2ResponseBodyEncryptFilter implements GlobalFilter, Ordered {
@Resource
private ModifyResponseBodyGatewayFilterFactory modifyResponseBodyGatewayFilterFactory;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return resBodyRewriter().filter(exchange, chain);
}
/**
* 修改请求体的filter
*/
@Bean
private GatewayFilter resBodyRewriter() {
return modifyResponseBodyGatewayFilterFactory.apply(new ModifyResponseBodyGatewayFilterFactory.Config().setRewriteFunction(
String.class, String.class, rewriteFunction()
));
}
/**
* 响应体修改方法
*/
private RewriteFunction<String, String> rewriteFunction() {
return (serverWebExchange, s) -> {
//此处对响应体进行修改、s为原响应体
return Mono.just("修改后的响应体");
};
}
/**
* 此处为必须配置!!!否则RewriteFunction不会生效!
* 引用自 <a href="https://gist.github.com/gatspy/a5cc3b26e9ada5c492e2b71689dd62b4">...</a>
*/
@Override
public int getOrder() {
return -2; //-1 is response write filter, call before that
}
}
Ordered
响应体执行 write 的过滤器 order 为 -1,所以必须要在执行 write 前执行修改响应体的方法。