spring-cloud-gateway Greenwich.SR2 2.1版本获取requestBody参数的解决方案

版本信息:

spring-boot: 2.1.2
spring-cloud: Greenwich.SR2

1.CacheBodyGatewayFilter

@Component
public class CacheBodyGatewayFilter implements Ordered, GlobalFilter {

  public static final String CACHE_REQUEST_BODY_OBJECT_KEY = "cachedRequestBodyObject";

  @Override
  public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    if (exchange.getRequest().getHeaders().getContentType() == null) {
      return chain.filter(exchange);
    } else {
      return DataBufferUtils.join(exchange.getRequest().getBody())
          .flatMap(dataBuffer -> {
            DataBufferUtils.retain(dataBuffer);
            Flux cachedFlux = Flux
                .defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
            ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(
                exchange.getRequest()) {
              @Override
              public Flux getBody() {
                return cachedFlux;
              }

            };
            exchange.getAttributes().put(CACHE_REQUEST_BODY_OBJECT_KEY, cachedFlux);

            return chain.filter(exchange.mutate().request(mutatedRequest).build());
          });
    }
  }

  @Override
  public int getOrder() {
    return Ordered.HIGHEST_PRECEDENCE;
  }
}

2.VerifyGatewayFilter

@Component
public class VerifyGatewayFilter implements GlobalFilter, Ordered {

  private static final Log log = LogFactory.getLog(VerifyGatewayFilter.class);

  public static final String CACHE_REQUEST_BODY_OBJECT_KEY = "cachedRequestBodyObject";

  @Override
  public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    Flux cachedBody = exchange.getAttribute(CACHE_REQUEST_BODY_OBJECT_KEY);
    String raw = toRaw(cachedBody);
    log.info(raw);
    return chain.filter(exchange);
  }

  @Override
  public int getOrder() {
    return Ordered.HIGHEST_PRECEDENCE + 100;
  }

  private static String toRaw(Flux body) {
    AtomicReference rawRef = new AtomicReference<>();
    body.subscribe(buffer -> {
      byte[] bytes = new byte[buffer.readableByteCount()];
      buffer.read(bytes);
      DataBufferUtils.release(buffer);
      rawRef.set(Strings.fromUTF8ByteArray(bytes));
    });
    return rawRef.get();
  }
}

测试结果:
spring-cloud-gateway Greenwich.SR2 2.1版本获取requestBody参数的解决方案_第1张图片
spring-cloud-gateway Greenwich.SR2 2.1版本获取requestBody参数的解决方案_第2张图片

你可能感兴趣的:(Springboot)