起因

网上大部分的Spring Boot修改请求返回的 header 的示例大多是通过 Filter 在chain.doFilter(request, response);之前修改 response 的 header 头,但是如果需要获取整个接口的执行耗时就不能使用 Filter 了。

因为在chain.doFilter(request, response);的时候 response 已经返回了,不能在之后修改 response 的 header 头

如果 Google 需要返回接口执行耗时,99.9%的结果都是通过打印 log(包括我之前)方式来输出接口的执行耗时,能满足需求但是在测试或者开发时候需要经常去盯着日志并不是非常方便

解决方案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Aspect
@Slf4j
@Order(88)
public class CostTimeAOP {
    /**
     * 切入点
     */
    @Pointcut(value = "execution(* *..controller..*.*(..))")
    public void aop() {
    }

    @Around("aop()")
    public Object doInvoke(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result;
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();

        try {
            result = pjp.proceed();
        } finally {
            long costTime = System.currentTimeMillis() - start;
            if (Objects.nonNull(response)) {
                response.setHeader("X-Response-Time", costTime + "ms");
            }
        }
        return result;
    }
}

效果

在 header 中返回接口执行耗时