Elegant Online User Count with Redis Sorted Sets (ZSET)
This article explains how to implement an online user counting feature by using Redis sorted sets, covering user identification (token or browser fingerprint), adding users with ZADD, querying current online users with ZRANGEBYSCORE, and cleaning up expired entries via ZREMRANGEBYSCORE and ZREM.
Online user counting is a common requirement; this article shows a practical implementation using Redis sorted sets (ZSET).
1. Determine online status
If the site requires login, use token validity; for public sites, use a unique identifier such as browser fingerprint. Libraries like FingerprintJS or ClientJS can generate a visitorId.
import FingerprintJS from '@fingerprintjs/fingerprintjs';
FingerprintJS.load().then(fp => {
fp.get().then(result => {
const visitorId = result.visitorId;
console.log(visitorId);
});
});The visitorId is stored in a cookie or header and sent to the backend.
2. Add online user with ZADD
Redis ZADD takes three arguments: key, score, member. The score is the expiration timestamp, ensuring each user has only one latest entry.
ZADD myzset 1 "one"In Java the code adds a token with an expiration time as score:
LocalDateTime expireTime = LocalDateTime.now().plusSeconds(expireTimeout);
String expireTimeStr = DateUtil.formatFullTime(expireTime);
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);3. Query online users with ZRANGEBYSCORE
ZRANGEBYSCORE returns members whose scores fall within a range. To get all currently online users, query from the current timestamp to +inf.
ZRANGEBYSCORE myzset 1 3 String now = DateUtil.formatFullTime(LocalDateTime.now());
Set<String> userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");The size of userOnlineStringSet equals the online count.
4. Periodic cleanup with ZREMRANGEBYSCORE
Expired entries are removed by deleting members whose scores are less than the current time.
ZREMRANGEBYSCORE myzset 1 3 String now = DateUtil.formatFullTime(LocalDateTime.now());
redisService.zremrangeByScore("user.active", "-inf", now);5. Remove user on logout with ZREM
When a user logs out, delete the corresponding member.
ZREM myzset "xxx" redisService.zrem("user.active", "xxx");Conclusion
The core idea is to maintain a Redis sorted set where each member represents an online user, the score stores the expiration time, and standard ZSET commands provide add, query, and cleanup operations, resulting in a simple and efficient online user count.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
SpringMeng
Focused on software development, sharing source code and tutorials for various systems.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
