1. 记录接口的响应时间
@Component
@Aspect
public class ActApiLogAop {
private static final Logger logger = LoggerFactory.getLogger(ActApiLogAop.class);
@Around("execution(* com.goaltree.rest.Controller.*(..)))")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
Stopwatch stopwatch = Stopwatch.createStarted();
Object o = pjp.proceed();
StringBuilder name=new StringBuilder(pjp.getTarget().getClass().getSimpleName()).append(":").append(pjp.getSignature().getName());
logger.info("接口:{},耗时:{}ms",
name,
stopwatch.elapsed(TimeUnit.MILLISECONDS));
return o;
}
}
2. 结合自定义注解使用
2.1 自定义注解
@Target({ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActivityVerify {
ActType type() default ActType.GLOBAL;
enum ActType{
GLOBAL
}
}
2.2 aop处理
@Component
@Aspect
public class ActivityVerifyAop {
private final static Logger log = LoggerFactory.getLogger(ActivityVerifyAop.class);
@Pointcut("@annotation(com.aop.ActivityVerify)")
public void activityAspect(){
}
@Around("activityAspect()")
public ResponseVO activityVerify(ProceedingJoinPoint joinPoint){
try {
if (true){
return ResponseVO.notInTime("活动为开始");
}else {
return (ResponseVO) joinPoint.proceed();
}
}catch (Throwable e){
log.error("验证活动时间异常", e);
return ResponseVO.fail("活动异常");
}
}
}