Created
July 30, 2015 13:13
-
-
Save xtea/3dd5f6b06a394094d6d9 to your computer and use it in GitHub Desktop.
Spring aspectj annotation sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.baidu.nightingale.common.aop; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
/** | |
* 使用Spring AOP切面进行能分析. 将此注解声明在方法上,可将方法执行时间统计在LOG中 | |
* | |
* @author lixiaomeng01 | |
* @date 2015-07-30 20:07 | |
*/ | |
@Target(ElementType.METHOD) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface TracePerformance { | |
/** | |
* 限定毫秒. | |
* | |
* @return | |
*/ | |
int limit(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.baidu.nightingale.common.aop; | |
import com.baidu.nightingale.common.log.LoggerHelper; | |
import org.aspectj.lang.ProceedingJoinPoint; | |
import org.aspectj.lang.annotation.Around; | |
import org.aspectj.lang.annotation.Aspect; | |
import org.springframework.stereotype.Service; | |
/** | |
* 通过AOP切面统计方法调用时间. | |
* | |
* @author lixiaomeng01 | |
* @date 2015-07-30 20:10 | |
*/ | |
@Aspect | |
@Service | |
public class TracePerformanceAspect { | |
/** | |
* 将超过限定的执行时间写入LOG日志. | |
* | |
* @param pjp | |
* @param tracePerformance | |
* @return | |
* @throws Throwable | |
*/ | |
@Around("@annotation(tracePerformance)") | |
public Object invoke(ProceedingJoinPoint pjp, final TracePerformance tracePerformance) | |
throws Throwable { | |
long begin = System.currentTimeMillis(); | |
// 被切面的方法. | |
Object result = pjp.proceed(); | |
long consumeMs = System.currentTimeMillis() - begin; | |
if (consumeMs > tracePerformance.limit()) { | |
String format = String.format("Target %s,Method %s eat %d ms", pjp.getTarget().getClass().getSimpleName(), | |
pjp.getSignature().toShortString(), consumeMs); | |
LoggerHelper.warn(TracePerformanceAspect.class, format); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment