前言
写代码的时候,我们有时候需要获取方法调用详细耗时。
一、一般做法
一般情况下,对于接口调用耗时,简单的做法都是通过System.currentTimeMillis()来获取时间,然后分别相减,获取某个代码块的执行耗时;
public ApiResponseEntity exTest() {
long start = System.currentTimeMillis();
BizException bizException = new BizException("myTest");
System.out.println("cost:" + (System.currentTimeMillis() - start));
throw bizException;
}
简单逻辑还好,但是如果我们的代码嵌套比较多,或者调用链路较长,该方法就显得不怎么合适了。
二、更优雅的做法
1. 考虑线程的概念
一般情况下,我们的方法调用都是发生在一个线程里,特别是一个网络请求。这样的话,咱们就可以考虑使用ThreadLocal来做这个事儿了。
2. 考虑如何计时
springboot启动的时候会显示花费了多少时间。跟代码进去发现,发现使用的StopWatch进行的计时。此处我们也使用StopWatch来进行计时。
3. 优化的计时方法类
public class StopWatchUtils {
public static ThreadLocal<StopWatch> CURRENT_STOP_WATCH = new ThreadLocal<>();
public static void start() {
if (Objects.nonNull(CURRENT_STOP_WATCH.get())) {
CURRENT_STOP_WATCH.remove();
}
StopWatch stopWatch = new StopWatch();
stopWatch.start();
CURRENT_STOP_WATCH.set(stopWatch);
print(null);
}
public static void check() {
if (

本文介绍了一种使用ThreadLocal和StopWatch进行方法调用耗时统计的优雅方式,并提供了具体实现及示例。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



