get the number of online by Play

本文介绍了一种利用缓存机制来统计在过去两分钟内活跃用户的解决方案。通过跟踪两个一分钟的计数器,并在每次用户请求时更新这些计数器,可以有效避免状态保持问题,并自动清除过时的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值