在开发 Web 应用时,监控接口的性能是非常重要的。通过记录接口的调用耗时,我们可以及时发现性能瓶颈,优化系统性能。本文将介绍如何在 Spring Boot 应用中使用 ServletRequestHandledEvent 来记录接口的调用耗时。
什么是 ServletRequestHandledEvent?
ServletRequestHandledEvent 是 Spring 框架提供的一个事件,它在每次 HTTP 请求处理完成后被发布。这个事件包含了请求的详细信息,如请求 URL、处理时间等。通过监听这个事件,我们可以获取到请求的处理时间,从而记录接口的调用耗时。这种方法不仅简单,而且不会对现有代码造成侵入。
创建事件监听器
为了实现接口调用耗时的记录,我们需要创建一个事件监听器来处理 ServletRequestHandledEvent 事件。以下是一个完整的示例代码:
package cn.aircas.listener;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.ServletRequestHandledEvent;
@Component
@Slf4j
public class RequestTimeEventListener implements ApplicationListener<ServletRequestHandledEvent> {
@Override
public void onApplicationEvent(ServletRequestHandledEvent event) {
Throwable failureCause = event.getFailureCause();
String failureMessage = failureCause == null ? "" : failureCause.getMessage();
if (failureCause != null) {
failureMessage = failureCause.getMessage();
}
String clientAddress = event.getClientAddress();
String requestUrl = event.getRequestUrl();
String method = event.getMethod();
long processingTimeMillis = event.getProcessingTimeMillis();
if (StrUtil.isEmpty(failureMessage)) {
log.info("clientAddress = {}, requestUrl = {}, method = {}, costTime = {}ms",clientAddress,requestUrl,method,processingTimeMillis);
} else {
log.error("clientAddress = {}, requestUrl = {}, method = {}, costTime = {}ms, error = {}",clientAddress,requestUrl,method,processingTimeMillis,failureMessage);
}
}
}
运行结果:
2024-12-30 14:16:10.055 [XNIO-1 task-1] [INFO] c.a.l.RequestTimeEventListener - [onApplicationEvent,24] - clientAddress = 127.0.0.1, requestUrl = /suborder/list, method = GET, costTime = 708ms
2024-12-30 14:19:35.448 [XNIO-1 task-1] [INFO] c.a.l.RequestTimeEventListener - [onApplicationEvent,24] - clientAddress = 127.0.0.1, requestUrl = /suborder/list, method = GET, costTime = 49ms