第一步:创建注解类
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 注解实现AOP装配
* 检测一个请求耗时情况
*/
@Target(METHOD)
@Retention(RUNTIME)
public @interface MetricTime {
String value();
}
第二步:将注解加到想要监听的方法上面
@GetMapping("/material")
@ApiOperation(value = "素材", notes = "素材 API")
@MetricTime("register")
public ApiResult cancelTopicTop(@RequestParam(value="pageNumber",required = false,defaultValue = "0") int pageNo,
@RequestParam(value="pageSize",required = false,defaultValue = "10") int pageSize,
@ApiParam(name = "kind", value = "种类:1:视频 2:图片", required = true) @RequestParam(value = "kind") Integer kind) {
PageHelper.startPage(pageNo,pageSize);
PageInfo<KeyValueVO> pageInfo = new PageInfo(topicService.getMaterial(kind));
return new ApiResult().withData(pageInfo);
}
第三步:编写具体的操作
import cn.com.community.admin.service.MetricTime;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* @Author:zhuchuanshun
* @Description: AOP 实现性能监控 一个请求耗时
* @Date: 2020/6/22 11:08
* @Modificd:
*/
@Aspect
@Component
public class MetricAspect {
@Around("@annotation(metricTime)")
public Object metric(ProceedingJoinPoint joinPoint, MetricTime metricTime) throws Throwable {
String name = metricTime.value();
long start = System.currentTimeMillis();
try {
return joinPoint.proceed();
} finally {
long t = System.currentTimeMillis() - start;
// 写入日志或发送至JMX:
System.out.println("该请求耗时 [Metrics] " + name + ": " + t + "ms");
}
}
}
这样就只要在方法上面添加 @MetricTime("register") 注解,就可以看到 请求耗的时间。
这样编写逻辑,将耗时打印一定的接口,另外打印出来。
参考:https://www.liaoxuefeng.com/wiki/1252599548343744/1310052317134882