Spring Cloud Gateway 截获请求的输入输出

介绍Spring Cloud Gateway截获请求的输入输出,主要包括Spring Cloud Gateway截获请求的输入输出使用实例、应用技巧、基本知识点总结和需要注意事项。

@Component
public class AuthGlobalFilter implements GlobalFilter , Ordered {

    @Override
    public int getOrder(){
        return -2;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        URI uri = exchange.getRequest().getURI();
        try {
            System.out.println(uri.toURL());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        ServerHttpRequest request= exchange.getRequest();
        if("POST".equalsIgnoreCase(request.getMethodValue())) {//判断是否为POST请求
            Flux<DataBuffer> body = request.getBody();
            AtomicReference<String> bodyRef = new AtomicReference<>();//缓存读取的request body信息
            body.subscribe(dataBuffer -> {
                CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
                DataBufferUtils.release(dataBuffer);
                bodyRef.set(charBuffer.toString());
            });//读取request body到缓存
            String bodyStr = bodyRef.get();//获取request body
            System.out.println("-----------------request body start-----------------");
            System.out.println(bodyStr);//这里是我们需要做的操作
            System.out.println("-----------------request body end-----------------");
            DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
            Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);

            request = new ServerHttpRequestDecorator(request) {
                @Override
                public Flux<DataBuffer> getBody() {
                    return bodyFlux;
                }
            };//封装我们的request
        }

        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @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 -> {
                        // 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("-----------------response body start-----------------");
                        System.out.println(s);
                        System.out.println("-----------------response body end-----------------");
                        //TODO,s就是response的值,想修改、查看即可随意而为
                        byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
        // replace response with decorator
        return chain.filter(exchange.mutate().request(request).response(decoratedResponse).build());
    }
}

注意order要小于-1

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/26/spring-cloud-gateway-intercepts-input-and-output-requests/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Spring Cloud Gateway 截获请求的输入输出
介绍Spring Cloud Gateway截获请求的输入输出,主要包括Spring Cloud Gateway截获请求的输入输出使用实例、应用技巧、基本知识点总结和需要注意事项。 @Compo……
<<上一篇
下一篇>>
文章目录
关闭
目 录