MqAspect.java 2.74 KB
package com.yanzuoguang.cloud.aop;

import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * LogsAspect(接口请求日志切面)
 *
 * @author: Kang
 * @time: 2018年04月25日 11:43
 */
@Aspect
@Component
public class MqAspect extends BaseRequestAspect {

    private static final String TAG = MqAspect.class.getSimpleName();

    @Value("${yzg.logMq:false}")
    private boolean logMq;

    /**
     * exec aop point aspect
     */
    @Pointcut("execution(* *..mq..*Consumer.*(..))")
    public void mqAspect() {
    }

    /**
     * 执行环形切面
     *
     * @param joinPoint
     * @return
     */
    @Around(value = "mqAspect()")
    public Object requestWebAround(ProceedingJoinPoint joinPoint) throws Throwable {
        boolean clear = isRabbit(joinPoint);
        if (clear) {
            Log.threadBegin();
        } else {
            clear = requestLogInit();
        }
        long start = requestLog(TAG, joinPoint);
        Object result = null;
        Exception ex = null;
        try {
            result = executeMethod(joinPoint);
            return result;
        } catch (Exception e) {
            // 消费消息出错
            result = ExceptionHelper.getError(e);
            ex = e;
            throw e;
        } finally {
            responseLog(logMq, clear, TAG, StringHelper.EMPTY, joinPoint, start, result, ex);
        }
    }

    private boolean isRabbit(ProceedingJoinPoint joinPoint) {
        if (joinPoint.getSignature() instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method targetMethod = methodSignature.getMethod();
            if ("YzgMqConsumer".equals(targetMethod.getDeclaringClass().getSimpleName())) {
                return false;
            }
            Annotation[] annotations = targetMethod.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType() != null
                        && "RabbitListener".equals(annotation.annotationType().getSimpleName())) {
                    return true;
                }
            }
        }
        return false;
    }

    private Object executeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        return joinPoint.proceed();
    }
}