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调试)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值