Track Online Users with Redis ZSET in Spring Boot
This guide explains how to implement an online user counting feature using Redis sorted sets (ZSET) in a Spring Boot application, covering user identification via tokens or browser fingerprinting, adding, querying, and cleaning up entries with zadd, zrangeByScore, zremrangeByScore, and zrem commands.
Introduction
The online user counting feature can be easily built with Redis sorted sets (ZSET). The core Redis commands used are zadd, zrangeByScore, zremrangeByScore and zrem.
Implementation Steps
1. How to determine if a user is online?
If the site requires login, you can check the validity of the user's token. For public sites, you need a custom rule such as IP, deviceId, or browser fingerprint. Using a browser fingerprint is recommended.
A browser fingerprint may include User-Agent, HTTP headers, screen resolution, timezone, language, and plugin details. Libraries like FingerprintJS or ClientJS simplify this process.
// Install
npm install @fingerprintjs/fingerprintjs
// Usage example
import FingerprintJS from '@fingerprintjs/fingerprintjs';
// Initialize the library
FingerprintJS.load().then(fp => {
// Get visitor ID
fp.get().then(result => {
const visitorId = result.visitorId;
console.log(visitorId);
});
});Store the obtained visitor ID in a cookie or header and pass it to the backend to identify the user.
2. Adding an online user with zadd
(1) zadd command – three parameters: key, score, member.
Example: ZADD myzset 1 "one"
(2) Add online user identifier 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 token to the sorted set
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);Using the current time plus an expiration interval as the score guarantees that each user has only one latest login state.
3. Querying online users with zrangeByScore
(1) zrangeByScore command
Example: ZRANGEBYSCORE myzset 1 3
(2) Get all currently online users
// Current timestamp
String now = DateUtil.formatFullTime(LocalDateTime.now());
// Query 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. Removing expired users with zremrangeByScore
(1) zremrangeByScore command
Example: ZREMRANGEBYSCORE myzset 1 3
(2) Periodically clean up offline users
// Current timestamp
String now = DateUtil.formatFullTime(LocalDateTime.now());
// Delete entries with scores between -inf and now
redisService.zremrangeByScore("user.active", "-inf", now);A scheduled task is needed because ZSET does not automatically remove offline users.
5. Removing a user on logout with zrem
(1) zrem command
Example: ZREM myzset "xxx"
(2) Delete the user when they log out
// Delete a specific member
redisService.zrem("user.active", "xxx");This removes the record from the ZSET, ensuring the user is marked offline.
Conclusion
The solution creates an online user identity set as the key, stores the user identifier as the member, and uses the expiration time as the score. By performing add, query, and delete operations on this set, you can efficiently track online users.
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.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.
