Search code examples
javaspring-bootmicrometerspring-micrometer

Track no of logged in users as micrometer metric?


I have spring boot application and I want to track no of logged in users using a metric ( I am using micrometer ) . My idea was to track /login rest call which we have and increment a guage. However I don't have a solution to decrease metric ( gauge count ) with user expire. If i want to decrease gauge based on fixed time after i increase the gauge, how can i do that ? Also my service has two instance, therefore to be consistent i plan to use load balancer session stickiness. With that i hope same user ( IP ) will land on same machine.

Following is my gauge

  AtomicInteger noOfLoggedInUsers = registry.gauge("logged.user.count", new AtomicInteger(0));

This is how i increment gauge

public int addUser(final String username) {
final String usernameVal = cache.get(username);
if (usernameVal == null) {
  cache.put(username, username);
  noOfLoggedInUsers.incrementAndGet();
}
return noOfLoggedInUsers.get();

}

I am using map to store unique users. Also i want to know is there a better way i can do to track no of logged in users.


Solution

  • There are a few things you can look into:

    1. Tomcat publishes a JMX counter called activeSessions: see the docs Micromeer has support for this, you can turn this on with server.tomcat.mbeanregistry.enabled=true in case of Spring Boot.

    2. You can schedule actions with a delay for the session expiry using Reactor: Mono.delay(ttl).subscribe(event -> noOfLoggedInUsers.decrementAndGet())
      Here's an example

    3. Since you are also maintaining a Map (that I don't really understand), you can take a look at Evictor that removes elements from a Concurrent Map after they expire (you might be able to reuse things from this project).