1. 概要

このチュートリアルでは、javax.servlet.http.HttpSessionListener 登録し、metricsを使用してWebアプリケーションでアクティブなセッションの数を追跡する方法を示します。

2. リスナーの定義

HTTPセッションリスナーをweb.xmlに登録できます。

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

または、サーブレット3環境では、@WebListenerを使用してリスナーを登録することもできます。 この場合、メインに注釈を付ける必要があります SpringBootApplication とのクラス @ServletComponentScan。

最後に、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>3.0.1</version>
</dependency>

クラスパスでメトリックコアを使用できるため、Counterオブジェクトを使用して同じHttpSessionListenerを記述できます。

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. 結論

このチュートリアルでは、 HttpSessionListener をWebアプリケーションのデプロイメント記述子に登録する方法と、2つのメカニズムを使用してアクティブなセッション数を監視する方法を説明しました。 最初のメカニズムは手巻きカウンターであり、2番目のメカニズムは成熟したメトリックライブラリに基づいています。

実装はサンプルのGitHubプロジェクトにあります。