
本文介绍一种基于 jdk 动态代理的轻量级方法计时方案,无需修改业务代码即可自动记录任意接口方法的执行耗时,适用于 spring 环境或纯 java 项目。
本文介绍一种基于 jdk 动态代理的轻量级方法计时方案,无需修改业务代码即可自动记录任意接口方法的执行耗时,适用于 spring 环境或纯 java 项目。
在性能分析与日志监控中,常需对关键服务方法的执行时间进行精确测量。虽然可手动在每处调用前后插入 StopWatch.start() / stop()(如原始循环所示),但这种方式侵入性强、易遗漏、难以维护。更优雅的解法是面向切面地封装计时逻辑——通过动态代理将计时行为透明织入目标方法调用链。
以下是一个简洁、无框架依赖的通用计时代理实现:
public class TimerProxy {
private static final Logger log = LoggerFactory.getLogger(TimerProxy.class);
private final Object delegate;
public TimerProxy(Object delegate) {
this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
}
@SuppressWarnings("unchecked")
public <t> T getInterface(Class<t> intf) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return (T) Proxy.newProxyInstance(
loader,
new Class>[]{intf},
(proxy, method, args) -> execute(method, args)
);
}
private Object execute(Method method, Object[] args) {
StopWatch sw = new StopWatch();
sw.start();
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("Failed to invoke method: " + method.getName(), e);
} finally {
sw.stop();
log.trace("Method '{}' executed in {} ms", method.getName(), sw.getTotalTimeMillis());
}
}
}</t></t>
✅ 使用方式示例(假设 SomeService 接口定义了 processFoo(Foo) 方法):
SomeService originalService = new SomeServiceImpl();
SomeService timedService = new TimerProxy(originalService).getInterface(SomeService.class);
// 后续所有调用均自动计时
for (Foo foo : foos) {
timedService.processFoo(foo); // 日志自动输出:Method 'processFoo' executed in 12 ms
}
⚠️ 注意事项:
- 目标服务必须实现接口(JDK 动态代理仅支持接口代理);
- 若需代理类而非接口(如 Spring AOP 的 CGLIB 场景),应改用
@Timed注解 + Spring AOP 或 Micrometer 集成; -
StopWatch来自 Spring Framework(org.springframework.util.StopWatch),确保已引入spring-core依赖; - 生产环境建议结合条件日志(如
log.isTraceEnabled())避免性能损耗; - 异常情况下仍会正确记录耗时(
finally块保障),便于定位慢请求与失败瓶颈。
该方案以最小侵入性实现了方法级性能可观测性,是构建可运维服务的重要基础实践之一。










