知識庫 / REST RSS 訂閱

會話監聽器示例 – 監控

REST
HongKong
5
04:11 AM · Dec 06 ,2025

1. 概述

本教程將演示如何註冊一個 jakarta.servlet.http.HttpSessionListener並使用 metrics 跟蹤 Web 應用程序中的活動會話數量。

2. 定義監聽器

web.xml 中註冊 HTTP Session 監聽器:

<web-app ...>
    <listener>
        <listener-class>com.baeldung.web.SessionListenerWithMetrics</listener-class>
    </listener>
</web-app>

或者,在 Servlet 3 環境中,我們可以使用 @WebListener 來註冊監聽器。在這種情況下,我們需要使用 @ServletComponentScan 註解來標記主 SpringBootApplication 類。

最後,我們還可以通過聲明一個 ServletListenerRegistrationBean Bean 來使用 Java 配置註冊監聽器:

@Bean
public ServletListenerRegistrationBean<SessionListenerWithMetrics> sessionListenerWithMetrics() {
   ServletListenerRegistrationBean<SessionListenerWithMetrics> 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();
    }
}

MetricRegistry – 應用程序中所有指標的中央註冊表 – 只是作為應用程序範圍內的靜態字段進行引用:

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 庫。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.