监听请求执行耗时时间
效果:
代码:
package com.zl.stu.studentInfoManage.authManagement.config;
import com.zl.stu.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* mvc处理
*
* @author z
* @date 2021-12-09 17:11
*/
@Aspect
@Component
@Order(1)
@Slf4j
public class CustomWebMvcAspectHandler {
/**
* 使用 org.springframework.web.bind.annotation.RestController 页面跳转没有监听
*/
@Pointcut("@within(org.springframework.web.bind.annotation.RequestMapping)")
public void pointCut() {
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint point) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
long b = System.currentTimeMillis();
Object[] args = point.getArgs();
Object result;
try {
// 执行方法
result = point.proceed(args);
} catch (Throwable var10) {
Result<Object> failed = Result.failed("网络请求失败,请稍后再试!");
result = failed;
log.error(CustomWebMvcAspectHandler.class.getName(), var10);
}
long e = System.currentTimeMillis();
log.info("远程主机: " + request.getRemoteAddr() + " --> 请求接口(" + request.getRequestURL() + ")执行耗时:" + (e - b) + "ms");
return result;
}
}
开启监听,实现MVC接口 WebMvcConfigurer ,添加开启aop注解 @EnableAspectJAutoProxy
@Configuration
@EnableAspectJAutoProxy
public class CustomWebMvcConfigurer implements WebMvcConfigurer {
}