记录请求时间

Posted wanhua-wu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了记录请求时间相关的知识,希望对你有一定的参考价值。

统计记录接口的请求时间:

package com.onloon.data.centralization.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.onloon.summer.common.utils.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求拦截器
 *
 * @author <a href="mailto:taojiagui@loonxi.com">云启</a>
 * @version 1.0 2017年5月12日
 * @since 1.0
 */
public class RequestInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(RequestInterceptor.class);

    // 存储请求额外信息
    private final ThreadLocal<RequestHolder> requestThread = new ThreadLocal<RequestHolder>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String uri = request.getRequestURI();
        if (logger.isInfoEnabled()) {
            logger.info("RequestInterceptor.preHandle execute uri={}", uri);
        }

        RequestHolder holder = new RequestHolder();
        holder.setStartTime(System.currentTimeMillis());
        holder.setUri(uri);
        requestThread.set(holder);
        logger.info("preHandle 当前线程:{},holder信息={}", Thread.currentThread().getName(), JsonUtil.toJsonString(holder));

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        RequestHolder holder = getRequestHolder();
        logger.info("afterCompletion 当前线程:{},holder信息={},当前时间={},请求消耗时间={} ms", Thread.currentThread().getName(),
                JsonUtil.toJsonString(holder), System.currentTimeMillis(),
                (System.currentTimeMillis() - holder.getStartTime()));
    }

    private RequestHolder getRequestHolder() {
        RequestHolder holder = requestThread.get();
        if (holder == null) {
            holder = new RequestHolder();
            requestThread.set(holder);
        }
        return holder;
    }

}

 

以上是关于记录请求时间的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

CSP核心代码片段记录

用于从 cloudkit 检索单列的代码模式/片段

discuz X3.1 源代码阅读,记录代码片段