java利用aop来记录接口的请求耗时、请求参数、请求url等详细信息

最近在项目里面需要对一些controller接口进行记录。记录的信息包括,接口的耗时、请求参数、请求url、是否成功、请求的ip地址。
最后利用aop切面编程。

@Order(1)
@Aspect
@Component
@Slf4j
public class BehaviorAop  {
   

    @Autowired
    BehaviorService behaviorService;

	/*
	* 我们对ApiOperation 这个注解进行切面,也就是说controller里面的方法只要被这个注解修饰,那么这个方法都会被记录详细信息,ApiOperation 这个注解是swagger的注解,当然我们也能自定义注解。
	/
    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void annotationTo() {
   
    }


    @Around("annotationTo()")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
   
        BehaviorRecordMo behaviorRecordMo = new BehaviorRecordMo();
        StopWatch watch = new StopWatch();
        try {
   
            log.debug("目标方法执行前...");
            //通过切面获取当前执行的方法
            Object target = joinPoint.getTarget();
            Signature sig = joinPoint.getSignature();
            MethodSignature msig = (MethodSignature) sig;
           Method method = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
            ApiOperation api
你可以使用AOP(面向切面编程)和拦截器来实现对Spring Boot项目的所有接口请求进行统计。以下是大致的实现步骤: 1. 定义一个注解(例如@RequestStatistics)用于标记需要统计请求次数的接口方法。 2. 创建一个切面类,在切面中编写统计请求次数、请求开始时间和结束时间的逻辑,并使用@Around注解将其绑定到@RequestStatistics注解上。 3. 创建一个拦截器,在拦截器中获取请求开始时间并将其存储到ThreadLocal中,请求结束时获取结束时间并计算请求耗时,将请求次数、请求开始时间和结束时间等信息存储到数据库或日志中。 以下是一个简单的示例代码: 首先定义@RequestStatistics注解: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RequestStatistics { } ``` 然后创建切面类RequestStatisticsAspect: ```java @Aspect @Component public class RequestStatisticsAspect { @Autowired private RequestStatisticsInterceptor requestStatisticsInterceptor; @Around("@annotation(com.example.demo.annotation.RequestStatistics)") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { return requestStatisticsInterceptor.around(joinPoint); } } ``` 在切面中使用@Around注解将其绑定到@RequestStatistics注解上,并调用RequestStatisticsInterceptor中的逻辑。 创建拦截器RequestStatisticsInterceptor: ```java @Component public class RequestStatisticsInterceptor extends HandlerInterceptorAdapter { private final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>(); @Autowired private RequestStatisticsService requestStatisticsService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { startTimeThreadLocal.set(System.currentTimeMillis()); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long startTime = startTimeThreadLocal.get(); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; String url = request.getRequestURI(); String method = request.getMethod(); String remoteAddr = request.getRemoteAddr(); requestStatisticsService.save(url, method, remoteAddr, startTime, endTime, duration); } } ``` 在拦截器中获取请求开始时间,请求结束时计算请求耗时并获取请求相关信息,并调用RequestStatisticsService将信息存储到数据库或日志中。 创建服务类RequestStatisticsService: ```java @Service public class RequestStatisticsService { @Autowired private RequestStatisticsRepository requestStatisticsRepository; @Transactional(propagation = Propagation.REQUIRES_NEW) public void save(String url, String method, String remoteAddr, long startTime, long endTime, long duration) { RequestStatisticsEntity entity = new RequestStatisticsEntity(); entity.setUrl(url); entity.setMethod(method); entity.setRemoteAddr(remoteAddr); entity.setStartTime(new Date(startTime)); entity.setEndTime(new Date(endTime)); entity.setDuration(duration); requestStatisticsRepository.save(entity); } } ``` 在服务类中将请求次数、请求开始时间和结束时间等信息存储到数据库中,这里使用了Spring Data JPA和@Transactional注解来实现事务管理。 最后,我们需要在Spring Boot的配置文件中开启AOP和拦截器: ```yaml spring: aop: auto: true mvc: interceptor: enabled: true exclude-path-patterns: /error ``` 以上是一个简单的实现方式,你可以根据具体业务需求进行修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值