欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringCloud Gateway自定义filter获取body中的数据为空的问题

程序员文章站 2022-03-21 12:49:36
最近在使用springcloud gateway进行网关的开发,我使用的版本是:springboot的2.3.4.release+springcloud的hoxton.sr8,在自定义过滤器时需要获取...

最近在使用springcloud gateway进行网关的开发,我使用的版本是:springboot的2.3.4.release+springcloud的hoxton.sr8,在自定义过滤器时需要获取serverhttprequest中body的数据,发现一直无法获取到数据,经过各种百度、谷歌,再加上自己的实践,终于找到解决方案:
1、首先创建一个全局过滤器把body中的数据缓存起来

package com.cloudpath.gateway.portal.filter;

import lombok.extern.slf4j.slf4j;
import org.springframework.cloud.gateway.filter.gatewayfilterchain;
import org.springframework.cloud.gateway.filter.globalfilter;
import org.springframework.core.ordered;
import org.springframework.core.io.buffer.databuffer;
import org.springframework.core.io.buffer.databufferutils;
import org.springframework.http.server.reactive.serverhttprequest;
import org.springframework.http.server.reactive.serverhttprequestdecorator;
import org.springframework.stereotype.component;
import org.springframework.web.server.serverwebexchange;
import reactor.core.publisher.flux;
import reactor.core.publisher.mono;

/**
 * @author mazhen
 * @classname cachebodyglobalfilter
 * @description 把body中的数据缓存起来
 * @date 2020/10/28 18:02
 */
@slf4j
@component
public class cachebodyglobalfilter implements ordered, globalfilter {

  // public static final string cache_request_body_object_key = "cachedrequestbodyobject";

  @override
  public mono<void> 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<databuffer> cachedflux = flux
                .defer(() -> flux.just(databuffer.slice(0, databuffer.readablebytecount())));
            serverhttprequest mutatedrequest = new serverhttprequestdecorator(
                exchange.getrequest()) {
              @override
              public flux<databuffer> 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;
  }

}

cachebodyglobalfilter这个全局过滤器的目的就是把原有的request请求中的body内容读出来,并且使用serverhttprequestdecorator这个请求装饰器对request进行包装,重写getbody方法,并把包装后的请求放到过滤器链中传递下去。这样后面的过滤器中再使用exchange.getrequest().getbody()来获取body时,实际上就是调用的重载后的getbody方法,获取的最先已经缓存了的body数据。这样就能够实现body的多次读取了。
值得一提的是,这个过滤器的order设置的是ordered.highest_precedence,即最高优先级的过滤器。优先级设置这么高的原因是某些系统内置的过滤器可能也会去读body,这样就会导致我们自定义过滤器中获取body的时候报body只能读取一次这样的错误如下:

java.lang.illegalstateexception: only one connection receive subscriber allowed.
	at reactor.ipc.netty.channel.fluxreceive.startreceiver(fluxreceive.java:279)
	at reactor.ipc.netty.channel.fluxreceive.lambda$subscribe$2(fluxreceive.java:129)
	at 

所以,必须把cachebodyglobalfilter的优先级设到最高。
2、在自定义的过滤器中尝试获取body中的数据

package com.cloudpath.iam.gateway.customerfilter;

import com.cloudpath.iam.gateway.utils.filterrequestresponseutil;
import lombok.extern.slf4j.slf4j;
import org.springframework.cloud.gateway.filter.gatewayfilter;
import org.springframework.cloud.gateway.filter.factory.abstractgatewayfilterfactory;
import org.springframework.core.io.buffer.databuffer;
import org.springframework.http.server.reactive.serverhttprequest;
import org.springframework.stereotype.component;
import reactor.core.publisher.flux;

import java.util.arrays;
import java.util.list;

/**
 * @author by mazhen
 * @classname testgatewayfilterfactory
 * @description 自定义过滤器获取body中的数据
 * @date 2020/10/27 14:38
 */
@component
@slf4j
public class testgatewayfilterfactory extends abstractgatewayfilterfactory<testgatewayfilterfactory.config> {


  @override
  public list<string> shortcutfieldorder() {
    return arrays.aslist("enabled");
  }

  public testgatewayfilterfactory() {
    super(config.class);
    log.info("loaded testgatewayfilterfactory");
  }

  @override
  public gatewayfilter apply(config config) {
    return (exchange, chain) -> {
      if (!config.isenabled()) {
        return chain.filter(exchange);
      }

      if (null != exchange) {
        serverhttprequest httprequest = exchange.getrequest();
          try {

            flux<databuffer> databufferflux = httprequest.getbody();
            //获取body中的数据
            string body = filterrequestresponseutil.resolvebodyfromrequest(databufferflux);
            log.info("body:{}",body);

          } catch (exception e) {
            log.error("异常:",e);
            return chain.filter(exchange);
          }
      }
      return chain.filter(exchange);
    };
  }


  public static class config {
    /**
     * 控制是否开启统计
     */
    private boolean enabled;

    public config() {
    }

    public boolean isenabled() {
      return enabled;
    }

    public void setenabled(boolean enabled) {
      this.enabled = enabled;
    }
  }
}

3、解析body的工具类

package com.cloudpath.iam.gateway.utils;


import org.springframework.core.io.buffer.databuffer;
import org.springframework.core.io.buffer.databufferutils;
import reactor.core.publisher.flux;
import java.nio.charbuffer;
import java.nio.charset.standardcharsets;
import java.util.concurrent.atomic.atomicreference;
import java.util.regex.matcher;
import java.util.regex.pattern;

/**
 * @author mazhen
 * @classname filterheadersutil
 * @description 过滤器请求/响应工具类
 * @date 2020/10/29 9:31
 */
public final class filterrequestresponseutil {

  /**
   * spring cloud gateway 获取post请求的body体
   * @param body
   * @return
   */
  public static string resolvebodyfromrequest( flux<databuffer> body){
    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
    return bodyref.get();

  }

  /**
   * 读取body内容
   * @param body
   * @return
   */
  public static string resolvebodyfromrequest2( flux<databuffer> body){
    stringbuilder sb = new stringbuilder();

    body.subscribe(buffer -> {
      byte[] bytes = new byte[buffer.readablebytecount()];
      buffer.read(bytes);
      databufferutils.release(buffer);
      string bodystring = new string(bytes, standardcharsets.utf_8);
      sb.append(bodystring);
    });
    return formatstr(sb.tostring());
  }

  /**
   * 去掉空格,换行和制表符
   * @param str
   * @return
   */
  private static string formatstr(string str){
    if (str != null && str.length() > 0) {
      pattern p = pattern.compile("\\s*|\t|\r|\n");
      matcher m = p.matcher(str);
      return m.replaceall("");
    }
    return str;
  }
}

解析body的内容,网上普遍是上面的两种方式,亲测resolvebodyfromrequest方法解析body中的数据,没有1024字节的限制。
ps:我传的参数有1万多字节。。。。。。。
大家可以按需所选。

到此这篇关于springcloud gateway自定义filter获取body中的数据为空的文章就介绍到这了,更多相关springcloud gateway自定义filter内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!