package com.company.microserviceuser.aop;
import java.util.Enumeration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import ******;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.stream.Stream;
/**
* 日志拦截.
*
* @author xindaqi
* @since 2020-10-23
*/
@Aspect
@Component
public class ApiCallLog {
@Resource
private AnnotationUtil annotationUtil;
private static ThreadLocal<Long> startTime = new ThreadLocal<>();
private Logger logger = LoggerFactory.getLogger(ApiCallLog.class);
/**
* 方法切入点,执行对应的方法
* 1. execution : 表达式主体
* 2. * :任意类型返回值
* 3. com.company.web.controller : AOP切片的包名
* 4. .. :当前包及子包
* 5. * : 类名,*表示所有类
* 6. .*(..) : 方法名,*表示任何方法名,..:任何参数类型
*/
@Pointcut("execution(* com.company.controller..*.*(..)) || execution(* com.company..exception..*.*(..))")
public void callLog() {
logger.info("Pointcut");
}
/**
* 切入方法执行前的方法
*
* @param joinPoint 反射接口(Interface)
* @throws Exception
*/
@Before("callLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
logger.info("===Api call aspect do before.===");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("URL: {}", request.getRequestURI());
logger.info("HTTP METHOD: {}", request.getMethod());
logger.info("IP: {}", request.getRemoteAddr());
logger.info("Class METHOD: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("Class name:{}", joinPoint.getTarget().getClass().getName());
Enumeration<String> enums = request.getParameterNames();
while(enums.hasMoreElements()) {
String paramName = enums.nextElement();
logger.info("Parameter name: {}", request.getParameter(paramName));
}
}
/**
* 切入方法执行结束后的方法
*/
@After("callLog()")
public void doAfter(JoinPoint joinPoint) {
logger.info("===Api call aspect do after.===");
}
/**
* 切入方法返回后执行方法
*/
@AfterReturning(value = "callLog()", returning = "returnValue")
public void doAfterReturing(JoinPoint joinPoint, Object returnValue) throws Exception {
if(joinPoint.getArgs().length != 0){
Stream.of(joinPoint.getArgs()).forEach(s -> annotationUtil.desensitization(s));
annotationUtil.desensitization(joinPoint.getArgs()[0]);
}
logger.info("ARGS: {}", joinPoint.getArgs());
long costTime = System.currentTimeMillis() - startTime.get();
logger.info("返回值:{}", returnValue);
logger.info("Time spending: {}ms", costTime);
logger.info("===Api call aspect do afterReturing.===");
startTime.remove();
}
}
package com.company.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 方法注解
*
* @author xindaqi
* @since 2020-12-26
*/
@Target({
ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name() default "xindaqi";
}
package com.company.microserviceuser.aop;
import java.util.Enumeration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.company.microserviceuser.utils.AnnotationUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.stream.Stream;
import com.company.microserviceuser.dto.LoginInputDTO;
/**
* 自定义方法切面.
*
* @author xindaqi
* @since 2020-10-23
*/
@Aspect
@Component
public class MyAop {
@Resource
private AnnotationUtil annotationUtil;
private static ThreadLocal<Long> startTime = new ThreadLocal<>();
private Logger logger = LoggerFactory.getLogger(ApiCallLog.class);
@Around("@annotation(com.company.annotation.MyAnnotation)")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
// 方法执行前
logger.info("===我是使用了MyAnnotation注解的方法:{}===", methodName);
startTime.set(System.currentTimeMillis());
Object obj = joinPoint.proceed();
// 方法执行后
long costTime = System.currentTimeMillis() - startTime.get();
startTime.remove();
logger.info("方法:{}执行时间:{}ms", methodName, costTime);
return obj;
}
}
package com.company.utils;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.company.annotation.MyAnnotation;
/**
* @author xindaqi
* @since 2020-10-26
*/
@Component
public class TimeProcessUtil {
private static final Logger logger = LoggerFactory.getLogger(TimeProcessUtil.class);
@MyAnnotation
public String timeGenerateFromPattern(String timePattern) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(timePattern);
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch(Exception e) {
logger.error("时间异常", e);
} finally {
logger.info("时间转换");
}
return LocalDateTime.now().format(dtf);
}
}
调用timeGenerateFromPattern()方法时会触发注解@MyAnnotation的逻辑。
序号 | 注解 | 描述 |
---|---|---|
1 | @PointCut | 适用于拦截指定包的类及方法,不适用于定义方法级别的注解 |
2 | @Around | 适用于任何方法拦截,相当于MethodInterceptor,CGLib代理,代理普通类,因此可以使用反射获取类的方法,使用该注解可以拦截任意级别的方法 |
【参考文献】
[1]https://www.jianshu.com/p/ca9eb94e71f1
[2]https://blog.csdn.net/u012843873/article/details/78624391
[3]https://www.cnblogs.com/pcheng/p/7099385.html
[4]https://blog.csdn.net/reee112/article/details/84937386