How to Accurately Track Online Users with Redis Sorted Sets
This guide explains how to implement an online user counting feature using Redis sorted sets, covering user identification methods, the essential zadd, zrangeByScore, zremrangeByScore, and zrem commands, along with code examples and a concise summary of the overall approach.
Online user counting can be implemented using Redis sorted sets (zset). The core methods are zadd, zrangeByScore, zremrangeByScore, and zrem.
1. How to identify whether a user is online
For sites that require login, online status is determined by the validity of the user's token. For public sites, you can use IP, deviceId, or browser fingerprint. Browser fingerprint libraries such as FingerprintJS or ClientJS can generate a unique identifier.
Example usage:
// Install: npm install @fingerprintjs/fingerprintjs
// Usage example:
import FingerprintJS from '@fingerprintjs/fingerprintjs';
// Initialize FingerprintJS library
FingerprintJS.load().then(fp => {
// Get visitor ID
fp.get().then(result => {
const visitorId = result.visitorId;
console.log(visitorId);
});
});The generated ID can be stored in a cookie or header and sent to the backend, where it is used as the member of the sorted set.
2. zadd command to add online users
The zadd command adds a member with a score (the expiration timestamp) to the sorted set.
// Set an expiration time for the user token
LocalDateTime expireTime = LocalDateTime.now().plusSeconds(expireTimeout);
String expireTimeStr = DateUtil.formatFullTime(expireTime);
// Add the user token to the sorted set
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);3. zrangeByScore command to query online users
Use zrangeByScore to retrieve members whose scores fall within a given range, which represents currently online users.
// Get the current timestamp
String now = DateUtil.formatFullTime(LocalDateTime.now());
// Query all users with scores from now to +inf
Set<String> userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");The size of userOnlineStringSet equals the number of online users.
4. zremrangeByScore command to periodically clean offline users
Since a sorted set does not automatically remove expired members, a scheduled task can delete entries whose scores are older than the current time.
// Get the current timestamp
String now = DateUtil.formatFullTime(LocalDateTime.now());
// Remove all members with scores between -inf and now
redisService.zremrangeByScore("user.active", "-inf", now);5. zrem command to delete a user on logout
When a user logs out, remove their token from the sorted set using zrem.
// Delete the member representing the user
redisService.zrem("user.active", "xxx");Summary
The core idea is to create a Redis sorted set where each online user is a member and the expiration timestamp is the score. By adding, querying, and removing members with the appropriate commands, you can efficiently track online user counts.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
