Spring-aop切面编程收集接口日志

场景:
项目需要实现每个接口请求都把url、所有参数、ip记录下来。

实现:

  1. 业务埋点,编码不优雅(否决)
  2. 基于spring aop注解方式拦截请求(pick~!)

实现流程

  1. 编写注解类
  2. 编写切面类
  3. 验证

编写注解类

InterfaceMsgAnnotation.java

package com.winnie.annotion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 接口信息注解类
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogInterfaceMsgAnnotation {
}

编写切面类

InterfaceMsgAspect.java

package com.winnie.aspect;

import com.alibaba.fastjson.JSONArray;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class InterfaceMsgAspect {
    private static final Logger logger = LoggerFactory.getLogger(InterfaceMsgAspect.class);

    @Pointcut("@annotation(com.epoch.wan37.annotion.LogInterfaceMsgAnnotation)")
    public void operator() {
    }

    @Around("operator()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object resultObj = null;
        InterfaceMessageLogVO logVO = new InterfaceMessageLogVO();
        try {
            Object[] args = joinPoint.getArgs();
            String requestJson = JSONArray.toJSONString(args);
            String methodName = joinPoint.getSignature().getName();
            Class clazz = joinPoint.getSignature().getDeclaringType();
            String interfaceFullname = joinPoint.getSignature().toString();
            // 做你想做的业务
            resultObj = joinPoint.proceed();
        } catch (Exception e){
            logger.error(e.getMessage());
            
        } finally {
           
        }

        return resultObj;
    }
}

验证

IndexController.java

@LogInterfaceMsgAnnotation
@RequestMapping("/getContract")
public void getContract(@RequestParam(value = "keyword", required = false) String keyword,
     // 进入之前会先被切面类调用
    return resultValue;
}

请求
http://localhost:8080/getContract?keyword=123
请求会被拦截并进入InterfaceMsgAspect ,验证完毕(可以debug调试)

你可能感兴趣的:(java,aop)