定义注解:
import java.lang.annotation.*;
/**
* Created by zsk on 9/21/15.
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CatLogProcessTime {
public String catEventType();
/**
* time in milliSecond
* @return
*/
public long threshledTime();
}
@Aspect
@Component
public class CatLogTimeAspect {
@Around("@annotation(com.lufax.recommend.aspect.CatLogProcessTime)")
public Object logProcessTime(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
try {
CatLogProcessTime annotation = method.getAnnotation(CatLogProcessTime.class);
Object[] params = joinPoint.getArgs();
String info = 2 == params.length ? params[1].toString() : "";
String catName = String.format("%s", params[0]);
long threshledTime = annotation.threshledTime();
if (end - start >= threshledTime) {
Cat.logEvent(annotation.catEventType(), catName, "0", info);
}
}catch (Throwable e){
Logger.warn(this, "Exception in CatLogTimeAspect");
}
return result;
}
}
开启Spring Aop 配置
<aop:aspectj-autoproxy proxy-target-class="true"/>
引用:
public class T {
@CatLogProcessTime(catEventType=CAT_KEY, threshledTime = THRESHOLD_MILLI_TIME)
public void function(...){}
<span style="white-space:pre"> </span>
public void f1(){
<span style="white-space:pre"> </span>this.function();
}
</pre><pre name="code" class="java">}
注意:
只有在使用到spring代理调用function时候,spring才会抓到Aop; 如果通过f1调用function时 不会进入Aop逻辑