HttpSessionListener Example – Monitoring – HttpSessionListener实例 – 监控

最后修改: 2013年 8月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial will show how to register a javax.servlet.http.HttpSessionListener and track the number of active sessions in the web application using metrics.

本教程将展示如何注册一个javax.servlet.http.HttpSessionListener并使用metrics跟踪Web应用程序中的活动会话数量。

2. Defining the Listener

2.定义听众

We can register the HTTP Session listener in the web.xml:

我们可以在web.xml中注册HTTP会话监听器:

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

Alternatively, in a Servlet 3 environment, we can use the @WebListener to register the listener as well. In this case, we need to annotate the main SpringBootApplication class with @ServletComponentScan.

另外,在Servlet 3环境中,我们也可以使用@WebListener来注册监听器。在这种情况下,我们需要在主SpringBootApplication类中注解@ServletComponentScan

Finally, we can also register the listener using Java configuration by declaring a ServletListenerRegistrationBean bean:

最后,我们还可以使用Java配置注册监听器通过声明一个ServletListenerRegistrationBeanbean

@Bean
public ServletListenerRegistrationBean<SessionListenerWithMetrics> sessionListenerWithMetrics() {
   ServletListenerRegistrationBean<SessionListenerWithMetrics> listenerRegBean =
     new ServletListenerRegistrationBean<>();
   
   listenerRegBean.setListener(new SessionListenerWithMetrics());
   return listenerRegBean;
}

3. The Basic Listener

3.基本听众

The simple listener will keep track of the number of active sessions at all times:

这个简单的监听器将随时跟踪活动会话的数量

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();
    }
}

The session listener will be triggered when the session is created – sessionCreated:

会话监听器将在会话创建时被触发 – sessionCreated

HttpSession session = request.getSession();

And destroyed – sessionDestroyed:

并销毁 – sessionDestroyed

session.invalidate();

This mechanism allows the current session count to be retrieved from the listener, but in order to have real-time monitoring and transparency, we need additional logic to actually retrieve the value and publish it.

这种机制允许从监听器中检索当前会话计数,但为了实现实时监控和透明性,我们需要额外的逻辑来实际检索该值并发布。

This is where the metrics library comes in – it comes with several out of the box reporters that allow this metric to be published with very little effort.

这就是指标库的作用–它配备了几个开箱即用的报告器,使这个指标的发布只需很少的努力。

4. The Listener With Metrics

4.有度量的听众

So, instead of rolling out our own custom monitoring solution, we’ll leverage the metrics library; we’ll need to add it to our pom:

因此,我们将利用指标库,而不是推出我们自己的监控解决方案;我们需要将其添加到我们的pom中。

<dependency>
    <groupId>com.codahale.metrics</groupId>
    <artifactId>metrics-core</artifactId>
    <version>3.0.1</version>
</dependency>

With metrics core is available on the classpath, we can write the same HttpSessionListener using a Counter object:

在classpath上有metrics core的情况下,我们可以使用一个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();
    }
}

The MetricRegistry – the central registry of all application metrics – is simply referenced in an application wide static field:

MetricRegistry–所有应用指标的中央登记处–只是在一个应用范围的静态字段中被引用。

public final class MetricRegistrySingleton {
    public static final MetricRegistry metrics = new MetricRegistry();
}

Publishing this metric and making it readily available to be monitored – for example to the standard logging system of the application – is straightforward:

发布这个指标并使其随时可被监测–例如向应用程序的标准日志系统–是很简单的。

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. Conclusion

5.结论

This tutorial illustrated how to register a HttpSessionListener in the deployment descriptor of the web application and how to monitor the active number of sessions using two mechanisms. The first mechanism is a hand-rolled counter and the second is based on the mature metrics library.

本教程说明了如何在Web应用程序的部署描述符中注册一个HttpSessionListener,以及如何使用两种机制来监控活动的会话数。第一种机制是一个手工滚动的计数器,第二种机制是基于成熟的metrics库。

The implementation can be found in the example GitHub project.

可以在GitHub 项目示例中找到该实现。