Implementing Online User Counting with Redis Sorted Sets (ZSET)
This article explains how to build an online user counting feature using Redis sorted sets (ZSET) by detailing the core commands (zadd, zrangeByScore, zremrangeByScore, zrem), user identification methods, and providing Java and JavaScript code examples, while also noting unrelated promotional content at the end.
The article introduces an online user counting feature and suggests using Redis sorted sets (ZSET) for its implementation.
Core Redis commands used are zadd , zrangeByScore , zremrangeByScore and zrem .
Step 1: Determine whether a user is online. For authenticated sites, check token validity; for public sites, use browser fingerprinting with libraries such as FingerprintJS or ClientJS.
// Install: npm install @fingerprintjs/fingerprintjs
// Usage example:
import FingerprintJS from '@fingerprintjs/fingerprintjs';
FingerprintJS.load().then(fp => {
fp.get().then(result => {
const visitorId = result.visitorId;
console.log(visitorId);
});
});Step 2: Add online users to a ZSET using zadd . Example command:
ZADD myzset 1 "one"
LocalDateTime expireTime = LocalDateTime.now().plusSeconds(expireTimeout);
String expireTimeStr = DateUtil.formatFullTime(expireTime);
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);Step 3: Query online users with zrangeByScore . Example command:
ZRANGEBYSCORE myzset 1 3
String now = DateUtil.formatFullTime(LocalDateTime.now());
Set
userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");Step 4: Periodically clean up expired users using zremrangeByScore :
String now = DateUtil.formatFullTime(LocalDateTime.now());
redisService.zremrangeByScore("user.active", "-inf", now);Step 5: Remove a user when they log out with zrem :
redisService.zrem("user.active", "xxx");The core logic is to maintain a ZSET where the key is the online‑user set, members are user identifiers, and scores are expiration timestamps, enabling efficient add, query, and cleanup operations.
In addition to the technical tutorial, the article contains promotional material for ChatGPT services, a paid community, and related offers, which are not part of the technical content.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.