How to Track Active Users with Redis Bitmaps: A Step‑by‑Step Guide
This article explains how to use Redis bit operations and bitmap keys to record daily user logins and efficiently compute statistics such as today’s active users, users active over the past three days, and users active within a week.
Scenario
When a user logs in, the login must be recorded for later statistical analysis. The main requirements are:
Number of users logged in today.
Users who have logged in within the last three days.
Users who have logged in within the last seven days.
Conventional Solution
Without Redis, the typical approach is to write a log entry at each login or insert a record into a database table, then run scheduled jobs to aggregate the data according to the requirements.
Redis Solution
Redis bit operations are ideal for this scenario because each bit can represent a binary state (0 or 1) indicating whether a specific user logged in on a given day. By storing a day's login information in a single key, each offset corresponds to a user ID.
Basic Bit Operations Example
(1) Set the value of a specific offset in a key to 0 or 1: setbit key 100 1 (2) Bitwise operations:
For example, given:
key1 -> 0101
key2 -> 0011AND operation: bitop and ret key1 key2 Result stored in ret is 0001.
OR operation: bitop or ret key1 key2 Result stored in ret is 0111.
(3) Count bits set to 1:
bitcount keyApplying the Solution
Assume today is 2016‑01‑18 and the key is named userlogin:20160118.
(1) User login: setbit userlogin:20160118 100 1 (2) Count users logged in today: bitcount userlogin:20160118 (3) Count users who logged in all of the last three days (bit value 1 in every day):
bitop and ret userlogin:20160116 userlogin:20160117 userlogin:20160118(4) Count users who logged in at least once in the last seven days (any bit set to 1):
bitop or ret userlogin:20160112 userlogin:20160113 userlogin:20160114 userlogin:20160115 userlogin:20160116 userlogin:20160117 userlogin:20160118Signed-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 High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
