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

Spring Cloud Gateway 获取请求体(Request Body)的多种方法

程序员文章站 2022-08-12 19:01:29
一、直接在全局拦截器中获取,伪代码如下private string resolvebodyfromrequest(serverhttprequest serverhttprequest){ flu...

一、直接在全局拦截器中获取,伪代码如下

private string resolvebodyfromrequest(serverhttprequest serverhttprequest){
 
  flux<databuffer> body = serverhttprequest.getbody();
 
  atomicreference<string> bodyref = new atomicreference<>();
 
  body.subscribe(buffer -> {
 
   charbuffer charbuffer = standardcharsets.utf_8.decode(buffer.asbytebuffer());
 
   databufferutils.release(buffer);
 
   bodyref.set(charbuffer.tostring());
 
  });
 
  return bodyref.get();
 
 }

存在的缺陷:其他拦截器无法再通过该方式获取请求体(因为请求体已被消费),并且会抛出异常

only one connection receive subscriber allowed.caused by: java.lang.illegalstateexception: only one connection receive subscriber allowed.

异常原因:实际上spring-cloud-gateway反向代理的原理是,首先读取原请求的数据,然后构造一个新的请求,将原请求的数据封装到新的请求中,然后再转发出去。然而我们在他封装之前读取了一次request body,而request body只能读取一次。因此就出现了上面的错误。

再者受版本限制

这种方法在spring-boot-starter-parent 2.0.6.release + spring cloud finchley.sr2 body 中生效,

但是在spring-boot-starter-parent 2.1.0.release + spring cloud greenwich.m3 body 中不生效,总是为空

二、先在全局过滤器中获取,然后再把request重新包装,继续向下传递传递

@override
 public gatewayfilter apply(namevalueconfig namevalueconfig) {
  return (exchange, chain) -> {
   uri uri = exchange.getrequest().geturi();
   uri ex = uricomponentsbuilder.fromuri(uri).build(true).touri();
   serverhttprequest request = exchange.getrequest().mutate().uri(ex).build();
   if("post".equalsignorecase(request.getmethodvalue())){//判断是否为post请求
    flux<databuffer> body = request.getbody();
    atomicreference<string> bodyref = new atomicreference<>();
    body.subscribe(databuffer -> {
     charbuffer charbuffer = standardcharsets.utf_8.decode(databuffer.asbytebuffer());
     databufferutils.release(databuffer);
     bodyref.set(charbuffer.tostring());
    });//读取request body到缓存
    string bodystr = bodyref.get();//获取request body
    system.out.println(bodystr);//这里是我们需要做的操作
    databuffer bodydatabuffer = stringbuffer(bodystr);
    flux<databuffer> bodyflux = flux.just(bodydatabuffer);
 
    request = new serverhttprequestdecorator(request){
     @override
     public flux<databuffer> getbody() {
      return bodyflux;
     }
    };//封装我们的request
   }
   return chain.filter(exchange.mutate().request(request).build());
  };
 }
 protected databuffer stringbuffer(string value) {
  byte[] bytes = value.getbytes(standardcharsets.utf_8);
 
  nettydatabufferfactory nettydatabufferfactory = new nettydatabufferfactory(bytebufallocator.default);
  databuffer buffer = nettydatabufferfactory.allocatebuffer(bytes.length);
  buffer.write(bytes);
  return buffer;
 }

该方案的缺陷:request body获取不完整(因为异步原因),只能获取1024b的数据。并且请求体超过1024b,会出现响应超慢(因为我是开启了熔断)。

三、过滤器加路线定位器

翻查源码发现readbodypredicatefactory里面缓存了request body的信息,于是在自定义router中配置了readbodypredicatefactory,然后在filter中通过cachedrequestbodyobject缓存字段获取request body信息。

/**
 * @description: 获取post请求的请求体
 * readbodypredicatefactory 发现里面缓存了request body的信息,
 * 于是在自定义router中配置了readbodypredicatefactory
 * @modified:
 */
@enableautoconfiguration
@configuration
public class routelocatorrequestboby{
   //自定义过滤器
 @resource
 private reqtracefilter reqtracefilter;
  
 @resource
 private ribbonloadbalancerclient ribbonloadbalancerclient;
 
 private static final string service = "/leap/**";
 
 private static final string http_prefix = "http://";
 
 private static final string colon = ":";
 
 @bean
 public routelocator myroutes(routelocatorbuilder builder) {
  //通过负载均衡获取服务实例
  serviceinstance instance = ribbonloadbalancerclient.choose("platform-service");
  //拼接路径
  stringbuilder forwardaddress = new stringbuilder(http_prefix);
  forwardaddress.append(instance.gethost())
    .append(colon)
    .append(instance.getport());
  return builder.routes()
    //拦截请求类型为post content-type application/json application/json;charset=utf-8
    .route(r -> r
        .header(httpheaders.content_type,
          mediatype.application_json_value + mediatype.application_json_utf8_value)
        .and()
        .method(httpmethod.post)
        .and()
        //获取缓存中的请求体
        .readbody(object.class, readbody -> {
         return true;
        })
        .and()
        .path(service)
        //把请求体传递给拦截器reqtracefilter
        .filters(f -> {
         f.filter(reqtracefilter);
         return f;
        })
        .uri(forwardaddress.tostring())).build();
 }
 
/**
 * @description: 过滤器,用于获取请求体,和处理请求体业务,列如记录日志
 * @modified:
 */
@component
public class reqtracefilter implements globalfilter, gatewayfilter,ordered {
 
 private static final string content_type = "content-type";
 
 private static final string content_type_json = "application/json";
  
 //获取请求路由详细信息route route = exchange.getattribute(gateway_route_bean)
 private static final string gateway_route_bean = "org.springframework.cloud.gateway.support.serverwebexchangeutils.gatewayroute";
 
 private static final string cache_request_body_object_key = "cachedrequestbodyobject";
 @override
 public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
  serverhttprequest request = exchange.getrequest();
  //判断过滤器是否执行
  string requesturl = requestutils.getcurrentrequest(request);
  if (!requestutils.isfilter(requesturl)) {
   string bodystr = "";
   string contenttype = request.getheaders().getfirst(content_type);
   string method = request.getmethodvalue();
   //判断是否为post请求
   if (null != contenttype && httpmethod.post.name().equalsignorecase(method) && contenttype.contains(content_type_json)) {
    object cachedbody = exchange.getattribute(cache_request_body_object_key);
    if(null != cachedbody){
     bodystr = cachedbody.tostring();
    }
   }
   if (httpmethod.get.name().equalsignorecase(method)) {
    bodystr = request.getqueryparams().tostring();
   }
   
   log.info("请求体内容:{}",bodystr);
  }
  return chain.filter(exchange);
 }
 
 
 @override
 public int getorder() {
  return 5;
 }
}

该方案优点:这种解决,一不会带来重复读取问题,二不会带来requestbody取不全问题。三在低版本的spring cloud finchley.sr2也可以运行。

缺点:不支持multipart/form-data(异常415),这个致命。

四、通过org.springframework.cloud.gateway.filter.factory.rewrite包下有个modifyrequestbodygatewayfilterfactory,顾名思义,这就是修改 request body 的过滤器工厂类。

@component
@slf4j
public class reqtracefilter implements globalfilter, gatewayfilter, ordered {
 
 @resource
 private iplatformfeignclient platformfeignclient;
 
 /**
  * httpheader,traceid的key名称
  */
 private static final string requestid = "traceid";
 
 private static final string content_type = "content-type";
 
 private static final string content_type_json = "application/json";
 
 private static final string gateway_route_bean = "org.springframework.cloud.gateway.support.serverwebexchangeutils.gatewayroute";
  
 
 @override
 public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
  serverhttprequest request = exchange.getrequest();
  //判断过滤器是否执行
  string requesturl = requestutils.getcurrentrequest(request);
  if (!requestutils.isfilter(requesturl)) {
   string bodystr = "";
   string contenttype = request.getheaders().getfirst(content_type);
   string method = request.getmethodvalue();
   //判断是否为post请求
   if (null != contenttype && httpmethod.post.name().equalsignorecase(method) && contenttype.contains(content_type_json)) {
    serverrequest serverrequest = new defaultserverrequest(exchange);
    list<string> list = new arraylist<>();
    // 读取请求体
    mono<string> modifiedbody = serverrequest.bodytomono(string.class)
      .flatmap(body -> {
       //记录请求体日志
       final string nid = saverequestoperlog(exchange, body);
       //记录日志id
       list.add(nid);
       return mono.just(body);
      });
 
    bodyinserter bodyinserter = bodyinserters.frompublisher(modifiedbody, string.class);
    httpheaders headers = new httpheaders();
    headers.putall(exchange.getrequest().getheaders());
    headers.remove(httpheaders.content_length);
 
    cachedbodyoutputmessage outputmessage = new cachedbodyoutputmessage(exchange, headers);
    return bodyinserter.insert(outputmessage, new bodyinsertercontext())
      .then(mono.defer(() -> {
       serverhttprequestdecorator decorator = new serverhttprequestdecorator(
         exchange.getrequest()) {
        @override
        public httpheaders getheaders() {
         long contentlength = headers.getcontentlength();
         httpheaders httpheaders = new httpheaders();
         httpheaders.putall(super.getheaders());
         httpheaders.put(requestid,list);
         if (contentlength > 0) {
          httpheaders.setcontentlength(contentlength);
         } else {
          httpheaders.set(httpheaders.transfer_encoding, "chunked");
         }
         return httpheaders;
        }
 
        @override
        public flux<databuffer> getbody() {
         return outputmessage.getbody();
        }
       };
 
       return chain.filter(exchange.mutate().request(decorator).build());
      }));
   }
   if (httpmethod.get.name().equalsignorecase(method)) {
    bodystr = request.getqueryparams().tostring();
    string nid = saverequestoperlog(exchange, bodystr);
    serverhttprequest userinfo = exchange.getrequest().mutate()
      .header(requestid, nid).build();
    return chain.filter(exchange.mutate().request(userinfo).build());
   }
 
  }
  return chain.filter(exchange);
 }
 
 
 /**
  * 保存请求日志
  *
  * @param exchange
  * @param requestparameters
  * @return
  */
 private string saverequestoperlog(serverwebexchange exchange, string requestparameters) {
  log.debug("接口请求参数:{}", requestparameters);
  serverhttprequest request = exchange.getrequest();
  string ip = objects.requirenonnull(request.getremoteaddress()).getaddress().gethostaddress();
  saveoperlogvo vo = new saveoperlogvo();
  vo.setip(ip);
  vo.setrequrl(requestutils.getcurrentrequest(request));
  vo.setreqmethod(request.getmethodvalue());
  vo.setrequestparameters(requestparameters);
 
  route route = exchange.getattribute(gateway_route_bean);
  //是否配置路由
  if (route != null) {
   vo.setsubsystem(route.getid());
  }
  resentity<string> res = platformfeignclient.saveoperlog(vo);
  log.debug("当前请求id返回的数据:{}", res);
  return res.getdata();
 }
 
 @override
 public int getorder() {
  return 5;
 }
}

该方案:完美解决以上所有问题

参考文档:

到此这篇关于spring cloud gateway 获取请求体(request body)的多种方法的文章就介绍到这了,更多相关spring cloud gateway 获取请求体内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!