zoukankan      html  css  js  c++  java
  • spring cloud gateway 读取requestBody,使用全局过滤器的方式。不需要在特定的Route中加readBody缓存predicate

    @Component
    public class RequestBodyAddCacheGlobalFilter implements GlobalFilter, Ordered {
        @Autowired
        ApplicationEventPublisher applicationEventPublisher;
    
        @Autowired
        ApplicationContext applicationContext;
    
        private final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
    
        public static final String CACHE_REQUEST_BODY_OBJECT_KEY = "cachedRequestBodyObject";
    
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            Class inClass = String.class;
            Class outClass = String.class;
            ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
            // TODO: flux or mono
            Mono<?> bodyMono = serverRequest
                    .bodyToMono(inClass)
                    .flatMap(body -> {
                        exchange.getAttributes().put(CACHE_REQUEST_BODY_OBJECT_KEY, body);
                        return Mono.just(body);
                    });
    
            BodyInserter bodyInserter = BodyInserters.fromPublisher(bodyMono, outClass);
            HttpHeaders headers = new HttpHeaders();
            headers.putAll(exchange.getRequest().getHeaders());
            CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
            return bodyInserter.insert(outputMessage, new BodyInserterContext())
                    .then(Mono.defer(() -> {
                        ServerHttpRequest decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
                            @Override
                            public Flux<DataBuffer> getBody() {
                                return outputMessage.getBody();
                            }
                        };
                        return chain.filter(exchange.mutate().request(decorator).build());
                    }));
    }
  • 相关阅读:
    Ubuntu下deb包的安装方法
    IP地址的分类——a,b,c 类是怎样划分的
    GDB十分钟教程
    【Github教程】史上最全github用法:github入门到精通
    java实现各种数据统计图(柱形图,饼图,折线图)
    MyEclipse 10官网下载地址以及破解方法
    二分查找
    游起来吧!超妹!
    [Python]linux自己定义Python脚本命令
    python无私有成员变量
  • 原文地址:https://www.cnblogs.com/zzq-include/p/12944680.html
Copyright © 2011-2022 走看看