1.创建annotation,代码如下
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InterfaceProperty {
/**
* 接口超时时间,单位毫秒.默认值400毫秒
*
* @return 设置的超时时间
*/
int timeout() default 400;
}
2.创建切面
@Component
@Aspect
public class SystemRequestAspect {
private static final Logger LOG = LoggerFactory.getLogger(SystemRequestAspect.class);
@Around(value = "execution(* com.csot.mass.background.controller..*.*(..))", argNames = "pjp")
public Object validator(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
Signature sig = pjp.getSignature();
MethodSignature msig = null;
if (!(sig instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只能用于方法");
}
msig = (MethodSignature) sig;
Object target = pjp.getTarget();
Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
String className = target.getClass().getName();
String methodName = currentMethod.getName();
/** 拦截的方法名称 */
try {
long start = System.currentTimeMillis();
Object obj = pjp.proceed(args);
long finish = System.currentTimeMillis();
long useTime = finish - start;
if (currentMethod.isAnnotationPresent(InterfaceProperty.class)) {
InterfaceProperty interfaceProperty = currentMethod.getAnnotation(InterfaceProperty.class);
if (useTime >= interfaceProperty.timeout()) {
LOG.info("接口超时",
className + "." + methodName,
useTime);
}
}
return obj;
} catch (Exception e) {
LOG.error(e.getMessage());
}
return null;
}
}