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());
                    }));
    }
  • 相关阅读:
    Windows7记事本的五大秘密
    深刻认识clientX,offsetX,screenX
    win7几个小技巧
    怎样开启Win7快速启动栏
    offsetLeft,Left,clientLeft的区别
    更改Windows7下图标查看方式
    让IE6、IE7、IE8支持CSS3的圆角、阴影样式
    windows7桌面右下角显示不止一个时间以及显示日期
    Win7开关机关闭Update方法
    jquery outerHeight方法 outerWidth方法
  • 原文地址:https://www.cnblogs.com/zzq-include/p/12944680.html
Copyright © 2011-2022 走看看