原创

通过Aop通过@FeignClient标注的接口中方法耗时

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

@Component
@EnableAspectJAutoProxy
public class FeignCostTimeAdvisor extends AbstractPointcutAdvisor {

    public FeignCostTimeAdvisor() {
        System.out.println("初始化!!!!");
    }

    public static boolean existsAnnotation(Class<?> cs, Class<? extends Annotation> annotation) {
        boolean rs = cs.isAnnotationPresent(annotation);
        if (!rs) {
            rs = cs.getSuperclass() != null && existsAnnotation(cs.getSuperclass(), annotation);
        }
        if (!rs) {
            Class<?>[] interfaces = cs.getInterfaces();
            for (Class<?> f : interfaces) {
                rs = existsAnnotation(f, annotation);
                if (rs) {
                    break;
                }
            }
        }
        if (!rs) {
            Annotation[] annotations = cs.getAnnotations();
            for (Annotation an : annotations) {
                rs = annotation.isAssignableFrom(an.getClass());
                if (rs) {
                    break;
                }
            }
        }
        return rs;
    }

    @Override
    public Pointcut getPointcut() {
        return new Pointcut() {
            @Override
            public ClassFilter getClassFilter() {
                return (Class<?> clazz) -> existsAnnotation(clazz, FeignClient.class);
            }

            @Override
            public MethodMatcher getMethodMatcher() {
                return MethodMatcher.TRUE;
            }
        };
    }

    @Override
    public Advice getAdvice() {
        return (MethodInterceptor) (MethodInvocation invocation) -> {
            long start = System.currentTimeMillis();
            Object result = invocation.proceed();
            long end = System.currentTimeMillis();
            System.out.println(invocation.getMethod() + ",耗时(ms):" + (end - start));
            return result;
        };
    }
}
正文到此结束
本文目录