切面记录日志
切面类
@Slf4j
@Aspect
@Component
public class AspectForFeign {
@Pointcut("execution(public * com.keke.remote..*Feign.*(..))")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
log.info("@Around:开始执行目标方法:{}ms", start);
Object result = null;
try {
result = joinPoint.proceed();
} catch (Exception e) {
System.out.println(e.getMessage());
}
long end = System.currentTimeMillis();
log.info("@Around:结束执行目标方法:{}ms", end);
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String methodName = methodSignature.getName();
log.info("方法名:{} 耗时:{}ms", methodName, end - start);
return result;
}
- 注意:返回结果如果不返回result,则目标对象实际返回值会被置为null
@Component
@Aspect
@Pointcut
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)
修饰符匹配(modifier-pattern?)
-
例:puiblic
返回值匹配(ret-type-pattern)
-
可以为表示任何返回值,全路径的类名等
类路径匹配(declaring-type-pattern?)
-
*Feign代表以Feign结尾的类
方法名匹配(name-pattern)
-
*代表所有
参数匹配((param-pattern))
-
多个参数间用“,”隔开,各个参数也可以用 * 来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(*,String) 表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(…)表示零个或多个任意参数
异常类型匹配(throws-pattern?)
-
?可选项
@Around
- 环绕增强,@Pointcut和@Around联合使用等同于:
@Around("execution(public * com.keke.remote..*Feign.*(..))")
切点拦截记录访问日志
拦截器数据源
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiAccess{
}
拦截器业务实现代码
@Aspect
@Component
@Slf4j
public class ApiAccessAspect {
@Pointcut("@annotation(com.keke.annotation.ApiAccess)")
public void pointcut() {}
@Around("pointcut()")
public Object apiAccessAspect(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
log.info("url:{}被访问了.....",request.getRequestURL().toString());
return joinPoint.proceed(joinPoint.getArgs());
}
}