1.导入pom依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
2.创建log实体类
@Builder
@Data
public class FlowApiLog implements Serializable {
private String id;
private String url;
private String createTime;
private String source;
private String ipaddr;
}
3.创建切面
@Slf4j
@Aspect
@Component
public class FlowApiAspect {
private static String YMDMHS = "yyyy-MM-dd HH:mm:ss";
@Autowired
private ApiLogService apiLogService;
@Pointcut(value = "@annotation(org.springframework.web.bind.annotation.GetMapping) ||" +
"@annotation(org.springframework.web.bind.annotation.PostMapping) ||" +
"@annotation(org.springframework.web.bind.annotation.PutMapping) ||" +
"@annotation(org.springframework.web.bind.annotation.DeleteMapping) ||" +
"@annotation(org.springframework.web.bind.annotation.RequestMapping) ")
public void flowApi(){
}
@Around(value = "flowApi()")
public Object flowControl(ProceedingJoinPoint joinPoint){
Object proceed = null;
long time = System.currentTimeMillis();
try {
proceed = joinPoint.proceed();
time = System.currentTimeMillis() - time;
log.info("方法执行消耗时间 = " + time);
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
saveFlowApi(joinPoint);
}
return proceed;
}
private void saveFlowApi(ProceedingJoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String re = "(本地前缀|部署上线的前缀)";
String url = request.getRequestURL().toString().replaceAll(re,"");
String date = DateFormatUtils.format(new Date(), YMDMHS);
FlowApiLog flowApiLog = FlowApiLog.builder()
.id(UUID.randomUUID().toString().replace("-",""))
.url(url)
.createTime(date)
.ipaddr(request.getRemoteAddr()).build();
apiLogService.insertApiLog(flowApiLog);
log.info("接口调用信息{}",flowApiLog);
}
}