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> <scope>runtime</scope>
</dependency> </dependency>
<!-- ops -->
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>3.0.1</version>
</dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency> <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; package org.baeldung.web;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionListener;
import org.baeldung.monitoring.MetricRegistrySingleton;
import com.codahale.metrics.Counter;
public class SessionListenerWithMetrics implements HttpSessionListener { public class SessionListenerWithMetrics implements HttpSessionListener {
private static int totalActiveSessions; private final AtomicInteger activeSessions;
private final Counter counterOfActiveSessions;
public SessionListenerWithMetrics() { public SessionListenerWithMetrics() {
super(); super();
activeSessions = new AtomicInteger();
counterOfActiveSessions = MetricRegistrySingleton.metrics.counter("web.sessions.active.count");
} }
// API // API
public static int getTotalActiveSession() { public final int getTotalActiveSession() {
return totalActiveSessions; return activeSessions.get();
} }
@Override @Override
public void sessionCreated(final HttpSessionEvent arg0) { public final void sessionCreated(final HttpSessionEvent event) {
totalActiveSessions++; activeSessions.incrementAndGet();
System.out.println("sessionCreated - add one session into counter"); counterOfActiveSessions.inc();
} }
@Override @Override
public void sessionDestroyed(final HttpSessionEvent arg0) { public final void sessionDestroyed(final HttpSessionEvent event) {
totalActiveSessions--; activeSessions.decrementAndGet();
System.out.println("sessionDestroyed - deduct one session from counter"); counterOfActiveSessions.dec();
} }
} }