java中可通过自定义@timecost注解结合aop实现方法耗时监控:定义运行时注解→编写@around切面记录起止时间→在spring bean方法上标注使用→可集成micrometer上报指标。

Java 中可以通过自定义注解 + AOP(面向切面编程)实现方法执行耗时的监控统计,核心是拦截目标方法调用,在前后记录时间差并输出或收集数据。
1. 定义耗时监控注解
创建一个运行时保留的自定义注解,用于标记需要监控的方法:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeCost {
String value() default ""; // 可选标识名,便于区分不同方法
}2. 编写 AOP 切面处理逻辑
使用 Spring AOP(需引入 spring-boot-starter-aop),在切面中获取注解、记录开始/结束时间,并打印或上报耗时:
@Aspect
@Component
public class TimeCostAspect {
<pre class="brush:java;toolbar:false;">private static final Logger log = LoggerFactory.getLogger(TimeCostAspect.class);
@Around("@annotation(timeCost)")
public Object recordTimeCost(ProceedingJoinPoint joinPoint, TimeCost timeCost) throws Throwable {
long start = System.currentTimeMillis();
try {
Object result = joinPoint.proceed(); // 执行原方法
long end = System.currentTimeMillis();
String methodName = joinPoint.getSignature().toShortString();
String label = StringUtils.hasText(timeCost.value()) ? timeCost.value() : methodName;
log.info("[TimeCost] {} took {} ms", label, end - start);
return result;
} catch (Throwable e) {
long end = System.currentTimeMillis();
String methodName = joinPoint.getSignature().toShortString();
String label = StringUtils.hasText(timeCost.value()) ? timeCost.value() : methodName;
log.warn("[TimeCost] {} failed after {} ms: {}", label, end - start, e.getMessage());
throw e;
}
}}
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
3. 在方法上使用注解
只需在需要监控的方法上添加 @TimeCost 即可,支持指定标签名方便识别:
@Service
public class UserService {
<pre class="brush:java;toolbar:false;">@TimeCost("user.find.byId")
public User findById(Long id) {
// 模拟数据库查询
try { Thread.sleep(120); } catch (InterruptedException e) { }
return new User(id, "Alice");
}
@TimeCost
public List<user> findAll() {
return Arrays.asList(new User(1L, "Bob"), new User(2L, "Cathy"));
}</user>}
4. 进阶:集成指标系统(如 Micrometer)
若需长期统计、聚合或对接 Prometheus,可用 Micrometer 记录 Timer 指标:
- 注入
Timer.Sample或直接使用Timer.builder(...).register(meterRegistry) - 在
around切面中将耗时作为观测值上报 - 配合 Grafana 展示 P90/P95 耗时、调用频次等
不复杂但容易忽略的是:确保目标方法被 Spring 容器管理(即通过 Bean 调用),否则 AOP 代理不会生效;异步方法需额外处理线程上下文传递。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










