tracking http sessions with metrics

This commit is contained in:
eugenp 2013-08-02 01:15:49 +03:00
parent 33cc1f297a
commit 6a77eb56b0
3 changed files with 41 additions and 9 deletions

View File

@ -92,6 +92,14 @@
<scope>runtime</scope>
</dependency>
<!-- ops -->
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>3.0.1</version>
</dependency>
<!-- test scoped -->
<dependency>

View File

@ -0,0 +1,13 @@
package org.baeldung.monitoring;
import com.codahale.metrics.MetricRegistry;
public final class MetricRegistrySingleton {
public static final MetricRegistry metrics = new MetricRegistry();
private MetricRegistrySingleton() {
throw new AssertionError();
}
}

View File

@ -1,32 +1,43 @@
package org.baeldung.web;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.baeldung.monitoring.MetricRegistrySingleton;
import com.codahale.metrics.Counter;
public class SessionListenerWithMetrics implements HttpSessionListener {
private static int totalActiveSessions;
private final AtomicInteger activeSessions;
private final Counter counterOfActiveSessions;
public SessionListenerWithMetrics() {
super();
activeSessions = new AtomicInteger();
counterOfActiveSessions = MetricRegistrySingleton.metrics.counter("web.sessions.active.count");
}
// API
public static int getTotalActiveSession() {
return totalActiveSessions;
public final int getTotalActiveSession() {
return activeSessions.get();
}
@Override
public void sessionCreated(final HttpSessionEvent arg0) {
totalActiveSessions++;
System.out.println("sessionCreated - add one session into counter");
public final void sessionCreated(final HttpSessionEvent event) {
activeSessions.incrementAndGet();
counterOfActiveSessions.inc();
}
@Override
public void sessionDestroyed(final HttpSessionEvent arg0) {
totalActiveSessions--;
System.out.println("sessionDestroyed - deduct one session from counter");
public final void sessionDestroyed(final HttpSessionEvent event) {
activeSessions.decrementAndGet();
counterOfActiveSessions.dec();
}
}