监控接口

package com.jhmk.cloudutil.interceptor;


/**
 * @author fzq(fuzhiqiang @ bjgoodwill.com)
 * @date 2022/4/24 9:48
 * @des API访问历史统计
 */

import com.jhmk.cloudutil.config.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;




@Component
@Aspect
public class ApiVisitHistory {


    Logger logger = LoggerFactory.getLogger(ApiVisitHistory.class);

    @Autowired
    RedisUtil redisUtil;

    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Value("${redis.expire.common}")
    private Long REDIS_EXPIRE;
    @Value("${redis.key.wiki}")
    private String REDIS_KEY_WIKI;


    /**
     * 定义切面
     * - 此处代表com.smile.demo.controller包下的所有接口都会被统计
     */
    @Pointcut("execution(* com.jhmk.cloudutil.himp..*.*(..))")
    public void pointCut() {

    }

    /**
     * 在接口原有的方法执行前,将会首先执行此处的代码
     */
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        String className = joinPoint.getSignature().getDeclaringType().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        logger.info("类名:{},方法名:{}接口接收访问", className, methodName);
        String hashKey = REDIS_DATABASE + REDIS_KEY_WIKI + "ApiVisitHistory";
        String key = className + methodName;
        Boolean ifExists = redisUtil.hHasKey(hashKey, key);
        if (false == ifExists) {
            redisUtil.hset(hashKey, key, 1);
        } else {
            redisUtil.hincr(hashKey, key, 1);
        }
        Object count = redisUtil.hget(hashKey, key);
        logger.info("类名:{},方法名:{}访问次数+1,已统计访问次数为:{}", className, methodName, count);
    }

    /**
     * 只有正常返回才会执行此方法
     * 如果程序执行失败,则不执行此方法
     */
    @AfterReturning(returning = "returnVal", pointcut = "pointCut()")
    public void doAfterReturning(JoinPoint joinPoint, Object returnVal) {
        String className = joinPoint.getSignature().getDeclaringType().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
//        logger.info("类名:{},方法名:{}接口执行成功,返回结果:{}", className, methodName, returnVal);

    }

    /**
     * 当接口报错时执行此方法
     */
    @AfterThrowing(throwing = "ex", pointcut = "pointCut()")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable ex) {
        String className = joinPoint.getSignature().getDeclaringType().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        logger.info("类名:{},方法名:{}接口执行出现报错,报错信息:{}", className, methodName, ex);
    }
}

你可能感兴趣的:(监控接口)