package com.hina.cloud.service.common.aspect;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;
@Slf4j
@Aspect
@Configuration(proxyBeanMethods = false)
public class RequestAspect {
@Autowired
private ObjectMapper objectMapper;
@Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
private void apiOperation() {
}
/**
* 入参打印
*/
@Before("apiOperation()")
public void doBefore(JoinPoint point) throws Throwable {
String methodDescription = getApiOperationValue(point);
for (Object arg : point.getArgs()) {
if (arg instanceof ServletRequest || arg instanceof MultipartFile[] || arg instanceof MultipartFile || arg instanceof ServletResponse) {
continue;
}
log.info("【{}】入参:{}{}", methodDescription, System.getProperty("line.separator"), objectMapper.writeValueAsString(arg));
}
}
/**
* 耗时
*
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("apiOperation()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Instant startTime = Instant.now();
Object result = proceedingJoinPoint.proceed();
log.info("执行耗时:{}毫秒", Duration.between(startTime, Instant.now()).toMillis());
return result;
}
/**
* 获取swagger 描述信息
*
* @param joinPoint 切点
* @return 描述信息
* @throws Exception
*/
public String getApiOperationValue(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
StringBuilder description = new StringBuilder();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description.append(method.getAnnotation(Operation.class).summary());
break;
}
}
}
return description.toString();
}
}
RequestAspect
最新推荐文章于 2023-04-23 18:03:55 发布