1. 概述
本教程將演示如何註冊一個jakarta.servlet.http.HttpSessionListener,並使用 metrics 跟蹤 Web 應用程序中的活動會話數量。
2. 定義監聽器
我們可以通過在 web.xml
<web-app ...>
<listener>
<listener-class>com.baeldung.web.SessionListenerWithMetrics</listener-class>
</listener>
</web-app>
或者,在 Servlet 3 環境中,我們可以使用 @WebListener
在這種情況下,我們需要用 @ServletComponentScan 註解主 SpringBootApplication 類。
最後,我們還可以通過 Java 配置 聲明一個 ServletListenerRegistrationBean bean 來註冊監聽器:
@Bean
public ServletListenerRegistrationBean<SessionListenerWithMetrics> sessionListenerWithMetrics() {
ServletListenerRegistrationBean<> listenerRegBean =
new ServletListenerRegistrationBean<>();
listenerRegBean.setListener(new SessionListenerWithMetrics());
return listenerRegBean;
}
3. 基本監聽器
簡單的監聽器會隨時跟蹤活躍會話數量:public class SessionListenerWithMetrics implements HttpSessionListener {
private final AtomicInteger activeSessions;
public SessionListenerWithMetrics() {
super();
activeSessions = new AtomicInteger();
}
public int getTotalActiveSession() {
return activeSessions.get();
}
public void sessionCreated(final HttpSessionEvent event) {
activeSessions.incrementAndGet();
}
public void sessionDestroyed(final HttpSessionEvent event) {
activeSessions.decrementAndGet();
}
}
會話監聽器將在會話創建時觸發 – sessionCreated:
HttpSession session = request.getSession();
並且銷燬時 – sessionDestroyed:
session.invalidate();
這個機制允許從監聽器檢索當前會話計數,但為了實現實時監控和透明度,我們需要額外的邏輯來實際檢索該值併發布它。
這就是指標庫發揮作用的地方 – 它隨附了幾個內置的報告器,可以藉助極小的努力發佈該指標。
4. 使用指標的監聽器
因此,我們不採用自建自定義監控解決方案,而是將利用指標庫;我們需要將其添加到我們的 pom 中:
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>4.2.21</version>
</dependency>
指標核心已在類路徑上可用,我們可以使用HttpSessionListener對象使用相同的Counter對象:
public class SessionListenerWithMetrics implements HttpSessionListener {
private final Counter counterOfActiveSessions;
public SessionListenerWithMetrics() {
super();
counterOfActiveSessions = MetricRegistrySingleton.metrics.counter("web.sessions.active.count");
}
public void sessionCreated(final HttpSessionEvent event) {
counterOfActiveSessions.inc();
}
public void sessionDestroyed(final HttpSessionEvent event) {
counterOfActiveSessions.dec();
}
}
指標註冊表——所有應用程序指標的中心註冊表——只是在應用程序級別的靜態字段中引用:
public final class MetricRegistrySingleton {
public static final MetricRegistry metrics = new MetricRegistry();
}
發佈此指標並使其可供監控——例如,到應用程序的標準日誌系統——非常簡單:
Logger logger = LoggerFactory.getLogger("com.baeldung.monitoring");
Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics).outputTo(logger).
convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
reporter.start(5, TimeUnit.MINUTES);
5. 結論
本教程介紹瞭如何在Web應用程序的部署描述符中註冊HttpSessionListener,以及如何使用兩種機制監控活動會話數量。第一種機制是手寫計數器,第二種機制則基於成熟的metrics庫。