get the number of online by Play
It's not an easy problem to solve because HTTP is a stateless protocol. A
user is never really "Connected" to your application.
The best you can do is to count requests made by distinct users during the X
last minutes.
One solution is to do like Loïc shown you. But using the cache in this way
is not very safe ... be aware of races conditions ...
You can keep the Users list as a static instance of your application but it
will only work if there is only one application instance
(however it's totally acceptable for small applications ...).
But using the cache can be a very nice way to handle this requirement. The
easy way is to use a counter and to increment it for each new
user. But the difficult part is to decrement the counter when the user is
"disconnected" (because you don't really know it). Using 2 counters
you can however handle it properly and to let the Cache automatically
discard older counters ...
Something like :
@Before
static void countUsers() {
// Track 2 counters of 1mn each
Integer lastMinute = (int)System.currentTimeMillis() / 60000;
// Counter keys
String counter1Key = lastMinute + "";
String counter2Key = (lastMinute-1) + "";
// Intialize counters
if(Cache.get(counter1Key) == null) Cache.add(counter1Key, 0L,
"2mn");
if(Cache.get(counter2Key) == null) Cache.add(counter2Key, 0L,
"2mn");
// Check if this user is already count
if(!session.contains("lastCount") ||
Integer.parseInt(session.get("lastCount")) < lastMinute - 1) {
Cache.incr(counter1Key);
session.put("lastCount", lastMinute);
}
// Now count users
Long counter1 = Cache.get(counter1Key, Long.class);
Long counter2 = Cache.get(counter2Key, Long.class);
// Save the result
renderArgs.put("nbUsers", counter1 + counter2);
}
In this way I count all users who have made a request during the last 2
minutes ...