利用Spring AOP切面和RabbitMQ消息队列实现高效的接口日志调用统计功能

总体的思想是:在需要日志统计的接口上加上自定义的注解(@OpLog),通过切面的方式获得接口调用时的参数信息,调用方信息等,同时为了不影响业务,采用MQ消息队列的方式执行日志入库的操作

0. 定义实体类

@Table(name = "op_log")
@Entity
@Data
@EqualsAndHashCode(callSuper = false)
public class OpLogEntity extends BaseEntity {
    /**
     * 接口名称
     */
    private String opApiName;
    /**
     * 方法签名
     */
    private String opMethodSignature;
    /**
     * 方法入参
     */
    private String opMethodArgs;
    /**
     * http方法 POST/GET/HEAD/FETCH/DELETE等
     */
    private String opHttpMethod;
    /**
     * http路径, 从controller的requestMapping到方法的requestMapping
     */
    private String opHttpPath;
    /**
     * url
     */
    private String opHttpUrl;
    /**
     * 日志记录时间(接口被调用时间)
     */
    private Date opStartTime;
    /**
     * 接口执行总时长(毫秒ms)
     */
    private Long opExecuteDuration;
    /**
     * 接口调用方id
     */
    private String opCallerId;
    /**
     * 接口调用方名字
     */
    private String opCallerName;
    /**
     * 接口调用方token
     */
    private String opCallerToken;
    /**
     * 接口调用方手机号
     */
    private String opCallerPhone;
    /**
     * 接口调用方ip
     */
    private String opCallerIp;
    /**
     * 接口执行结果: 1-正常返回,0-抛出异常
     */
    private String opResultFlag;
    /**
     * 业务执行结果
     */
    private String opBusinessFlag;
    /**
     * 接口执行抛出异常时的堆栈信息
     */
    private String opResultThrow;
}

1. 定义注解

// OpLog.java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface OpLog {
    String apiName();
}

2. Aspect切面处理类

// OpLogAspect.java 已做简化
@Aspect
@Component
public class OpLogAspect {
    private static Logger logger = LoggerFactory.getLogger(OpLogAspect.class);
    
    @Autowired
    private RabbitMqSender rabbitMqSender;
    
    private volatile JoinPoint joinPoint;
    private long startTime;
    private OpLogVO opLogVO;
    
    @Pointcut(value = "@annotation(com.example.aop.OpLog)")
    public void opLogPointCut() {
    }
    
    // 在before时通过attributes 、signature等对象获取接口信息保存到opLogVO中
    @Before(value = "opLogPointCut()")
    public void logBefore(JoinPoint joinPoint) {
        try {
            this.joinPoint = joinPoint;
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            DateTime now = DateUtil.date();
            startTime = now.toTimestamp().getTime();
            opLogVO = new OpLogVO();
            opLogVO.setOpStartTime(now.toJdkDate());
            Signature signature = joinPoint.getSignature();
            if (signature instanceof MethodSignature) {
                String apiName = ((MethodSignature) signature).getMethod().getAnnotation(OpLog.class).apiName();
                opLogVO.setOpApiName(apiName);
                setMethodAndPath(joinPoint, (MethodSignature) signature);
                setMethodArgs(joinPoint, (MethodSignature) signature);
            }
            opLogVO.setOpMethodSignature(signature.toString());
            if (attributes instanceof ServletRequestAttributes) {
                HttpServletRequest servletRequest = ((ServletRequestAttributes) attributes).getRequest();
                opLogVO.setOpHttpUrl(servletRequest.getRequestURL().toString());
                opLogVO.setOpCallerIp(getIpAddress(servletRequest));
            }
        } catch (Exception e) {
            logger.error("切面处理操作日志异常!logBefore-", e);
        }
    }
    
    // AfterReturning表示接口正常返回,将保存了信息的OpLogVO对象发送到MQ队列
    @AfterReturning(value = "opLogPointCut()", returning = "returnValue")
    public void logAfterReturning(JoinPoint joinPoint, Object returnValue) {
        if (this.joinPoint == joinPoint) {
            try {
                long executeDuration = System.currentTimeMillis() - startTime;
                opLogVO.setOpExecuteDuration(executeDuration);
                opLogVO.setOpResultFlag("1");
                // rabbitMqSender是对RabbitMQ的简单封装,最终调用的RabbitTemplate.convertAndSend(String routingKey, Object object)方法
                rabbitMqSender.send(RabbitConfigCommon.OP_LOG_MQ, JSONUtil.toJsonStr(opLogVO));
            } catch (Exception e) {
                logger.error("切面处理操作日志异常!logAfterReturning-", e);
            }
        }
    }
    
    // AfterThrowing表示接口出现异常,将异常堆栈保存到OpLogVO对象发送到MQ队列
    @AfterThrowing(value = "opLogPointCut()", throwing = "throwValue")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable throwValue) {
        if (this.joinPoint == joinPoint) {
            try {
                long executeDuration = System.currentTimeMillis() - startTime;
                opLogVO.setOpExecuteDuration(executeDuration);
                opLogVO.setOpResultFlag("0");
                // import cn.hutool.core.exceptions.ExceptionUtil;
                String stacktrace = ExceptionUtil.stacktraceToString(throwValue);
                opLogVO.setOpResultThrow(StrUtil.sub(stacktrace, 0, 450));
                rabbitMqSender.send(RabbitConfigCommon.OP_LOG_MQ, JSONUtil.toJsonStr(opLogVO));
            } catch (Exception e) {
                logger.error("切面处理操作日志异常!logAfterThrowing-", e);
            }
        }
    }
}

3. RabbitMQ消费者

// RabbitMqReceiver.java
@Component
public class RabbitMqReceiver {
    // OpLogBusi即保存opLogVO到数据库的Business,此处不再展开说明
    @Autowired
    private OpLogBusi opLogBusi;
    
     @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitConfigCommon.OP_LOG_MQ, durable = "true"),
            exchange = @Exchange(value = "ALL"),
            key = RabbitConfigCommon.OP_LOG_MQ))
    public void consumeSaveOpLogMessage(String opLogVO) {
        // opLogBusi.saveOpLog() --> opLogService.save() --> opLogDao.save()
        opLogBusi.saveOpLog(JSONUtil.toBean(opLogVO, OpLogVO.class));
    }
}

4. 使用

    // PersonController.java
    只需在方法上加上@OpLog注解即可
    @OpLog(apiName = "查询个人信息")
    @RequestMapping(value = "/getPersonInfo",method = RequestMethod.POST)
    public ResultBean getPersonInfo(@RequestBody QueryPersonInfo queryPersonInfo) {
        
    }

5. 总结

@OpLog() → Aspect切面 → 分析获取接口调用信息 → 发送到MQ队列 → 接收并消费消息 → 保存到数据库

你可能感兴趣的:(利用Spring AOP切面和RabbitMQ消息队列实现高效的接口日志调用统计功能)