Gateway 获取 RequestBody

Gateway 获取 RequestBody,第1张

Gateway 获取 RequestBody

百度搜了一大堆文献,全部什么改源码,封装Body啥的,都很复杂,这里直接利用的 Gateway 源码中的 CacheRequestBodyGatewayFilterFactory 缓存了RequestBody,我们先让它执行,然后执行我们的逻辑,即可直接取出RequestBody。

Gateway版本:

org.springframework.cloud:spring-cloud-starter-gateway:3.1.1

直接上代码:

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.*;

@Component
public class RequestFilterFactory extends AbstractGatewayFilterFactory {

    private static final Logger log = LoggerFactory.getLogger(RequestFilterFactory.class);

    static {
        log.info("RequestFilterFactory init");
    }

    @Autowired
    private RequestFilter requestFilter;

    public RequestFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        log.info("进入 RequestFilterFactory");
        return requestFilter;
    }

    public static class Config {}

    @Component
    public static class RequestFilter  implements GatewayFilter, Ordered {
        private static final Logger log = LoggerFactory.getLogger(RequestFilter.class);

        static {
            log.info("RequestFilter init");
        }

        @Override
        public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            log.info("进入 RequestFilter");
            String requestBody = exchange.getAttribute(ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR);
            log.info("requestBody:{}", requestBody);
            return chain.filter(exchange);
        }

        @Override
        public int getOrder() {
            // 运行顺序:CacheRequestBodyGatewayFilterFactory -> RequestFilterFactory 
            return 2;
        }
    }
}


yml 配置:

spring:
  cloud:
    gateway:
      default-filters:
        - name: CacheRequestBody
          args:
            bodyClass: java.lang.String
        - name: RequestFilterFactory

这里我设置的是全局的过滤器,可根据个人需求设置在相应路由的filters下。

​如有错误,欢迎指正;如有侵权,请联系作者。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/906235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存