使用zuul过滤器监听接口响应情况

参考深入理解Zuul

一、过滤器类型与请求生命周期

Zuul大部分功能都是通过过滤器来实现的。Zuul中定义了四种标准过滤器类型,这些过滤器类型对应于请求的典型生命周期。

(1) PRE:这种过滤器在请求被路由之前调用。我们可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等。

(2) ROUTING:这种过滤器将请求路由到微服务。这种过滤器用于构建发送给微服务的请求,并使用Apache HttpClient或Netfilx Ribbon请求微服务。

(3) POST:这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。

(4) ERROR:在其他阶段发生错误时执行该过滤器。

除了默认的过滤器类型,Zuul还允许我们创建自定义的过滤器类型。例如,我们可以定制一种STATIC类型的过滤器,直接在Zuul中生成响应,而不将请求转发到后端的微服务。
2017227192827529.png

二、使用过滤器对请求响应情况做日志监控

1.PRE过滤器添加请求进入时间

package com.kaicom.mes.monitor.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

/**
 * @Author: BillYu
 * @Description:
 * @Date: Created in 下午3:56 2018/11/20.
 */
@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.set("startTime",System.currentTimeMillis());

        return null;
    }
}

2.POST类型过滤器获取请求返回信息

package com.kaicom.mes.monitor.filter;

import com.kaicom.mes.monitor.handle.ApiInfo;
import com.kaicom.mes.monitor.handle.MqClient;
import com.kaicom.mes.util.GsonUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @Author: BillYu
 * @Description:
 * @Date: Created in 下午3:57 2018/11/20.
 */
@Component
public class CollectFilter extends ZuulFilter {
    @Autowired
    private MqClient mqClient;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //请求类型
        String method = request.getMethod();
        System.out.println("method:" + method);
        Map<String, String[]> params = request.getParameterMap();
        //请求参数
        String paramsStr = params.toString();
        System.out.println("param:" + paramsStr);
        //请求开始时间
        long statrtTime = (long) context.get("startTime");
        System.out.println("startTime" + statrtTime);
        //请求的uri
        String uri = request.getServletPath();
        System.out.println("uri:" + uri);
        System.out.println("servletpath:" + request.getPathInfo());
        //请求的状态
        int statusCode = context.getResponseStatusCode();
        System.out.println("code:" + statusCode);
        System.out.println("responese:"+context.getResponseBody());
        try {
            InputStream reqIs = context.getRequest().getInputStream();
            if (reqIs != null) {
                System.out.println("request:" + IOUtils.toString(reqIs, "utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //请求耗时
        long duration = System.currentTimeMillis() - statrtTime;
        System.out.println("duration:" + duration);
        ApiInfo apiInfo = new ApiInfo();
        apiInfo.setEndTime(System.currentTimeMillis());
        apiInfo.setStartTime(statrtTime);
        apiInfo.setUri(uri);
        apiInfo.setStatus(statusCode);
        mqClient.send(GsonUtil.toJson(apiInfo));
        //获取返回信息
        InputStream stream = RequestContext.getCurrentContext().getResponseDataStream();
        try {
            String body = IOUtils.toString(stream);
            System.err.println("response:"+body);
            //如果不进行手动赋值会导致返回为空
            RequestContext.getCurrentContext().setResponseBody(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

三、日志信息处理

笔者采用的做法是将日志信息发送到rabbitmq消息队列中,在另一个独立的监控服务中对消息队列中的日志信息进行处理,如果在zuul中直接处理会增加请求响应时间,在对rabbitmq消息处理时可以考虑进行批处理,避免频繁计算和占用数据库连接资源。

已有 12 条评论
  1. Buy Cialis

    Hi there to all, how is everything, I think every one is getting more from this web page, and your views are pleasant in favor of new viewers.

    Buy Cialis November 22nd, 2019 at 08:29 pm回复
  2. StevWews

    Levitra Generika Online Bestellen Buy Cialis Propecia Efficacy Real Free Shipping Stendra Tablets Worldwide Next Day Delivery

    StevWews January 17th, 2020 at 06:38 pm回复
  3. MatInfoge

    Purchase Nexium Online No Prescription Amoxicillin For Toddlers Buy Cialis Can Amoxicillin Kill Yeast Potenzmittel Viagra Cialis Und Kamagra Comprar Cytotec En Online Usa

    MatInfoge January 18th, 2020 at 03:48 am回复
  4. LesAstona

    Viagra For Sale In Pennsylvania http://cialibuy.com - cialis Non Prescription Levitra Cialis Cialis Viagra Levitra

    LesAstona January 21st, 2020 at 07:16 am回复
  5. LesAstona

    Original Viagra Online Bestellen http://buyciaonlinex.com/# - order cialis online Levitra Online In Usa Buy Cialis Propecia Minoxidil Together

    LesAstona February 4th, 2020 at 04:54 pm回复
  6. StevWews

    Canadian Online Drug Site Reviews http://buycialisuss.com - Buy Cialis Amoxicillin Dosage For Sinus Infection Buy Cialis Ciprofloxacin And Amoxicillin Taken Togather

    StevWews February 14th, 2020 at 01:51 pm回复
  7. LesAstona

    Cialis 20mg No Prescription http://cheapcialisir.com - Cialis Precio De La Viagra En Farmacias buy generic cialis Cheapest Levitra Professional

    LesAstona February 24th, 2020 at 05:37 pm回复
  8. MatInfoge

    Levothyroxine Canada No Prescription https://buyciallisonline.com/# - Buy Cialis Priligy Forum Uk Cialis Purchasing Generic Stendra On Line

    MatInfoge February 26th, 2020 at 02:49 pm回复
  9. EllEarnef

    Amoxicillin Not Refrigerated http://cheapcialisir.com - Cialis Expiration Date On Amoxicillin Cheap Cialis Dosage For Amoxicillin 400 5ml

    EllEarnef March 4th, 2020 at 01:07 pm回复
  10. Stepsok

    Awc Conadian Pharmacy Promo Code Cialis Que Es Viagra Soft Buy Cialis Comprar Cialis 10 Mg

    Stepsok March 12th, 2020 at 12:07 pm回复
  11. Stepsok

    Levitra 20 Mg Problemi Cialis Comprar Cialis En Mendoza Cialis Meds From Canada No Prescription

    Stepsok March 21st, 2020 at 05:24 pm回复
  12. Janmit

    Cheapest Prices On Generic Cialis cialis online without prescription Cialis Gefahrlich buy cialis generic online Viagra Para Distrofia Muscular

    Janmit March 27th, 2020 at 10:36 pm回复
发表新评论