Using Redis Bitmaps for Efficient User Sign‑in Statistics with PHP
This article explains Redis bitmap data structures, introduces common bitmap commands such as BITSET, BITGET, and BITCOUNT, and provides a complete PHP example that records user sign‑ins and calculates daily sign‑in counts using Redis bit operations.
Bitmaps are a data structure used for compact storage and fast bit‑level operations. Redis, a popular NoSQL database, supports bitmap commands that enable efficient statistics. This article introduces the basic concepts of Redis bitmap operations and demonstrates their use with a PHP code example for precise user sign‑in counting.
1. Introduction to Redis Bitmap Operations
A bitmap consists of a sequence of binary bits, each being either 0 or 1. Redis provides a set of commands—BITSET, BITGET, BITCOUNT, etc.—to create, read, modify, and count bits within a bitmap.
2. Common Redis Bitmap Commands
• Create or set a bit: BITSET key offset value (e.g., BITSET mykey 0 1 ) • Retrieve a bit: BITGET key offset (e.g., BITGET mykey 0 ) • Count bits set to 1: BITCOUNT key [start end] (e.g., BITCOUNT mykey 0 9 counts bits 0‑9 that are 1)
3. Redis Bitmap Operation Example
The following PHP script demonstrates how to use Redis bitmap commands to implement a daily user sign‑in statistics feature.
setbit($key, $userId, 1);
}
function getUserSignCount($date)
{
global $redis;
$key = 'user_sign:' . $date;
$count = $redis->bitcount($key);
return $count;
}
$user1 = 1;
$user2 = 2;
$date = date('Ymd');
userSign($user1, $date);
userSign($user2, $date);
$count = getUserSignCount($date);
echo "User sign‑in count: {$count}";
?>The script defines userSign to set a bit for a specific user on a given date and getUserSignCount to count the number of bits set to 1, representing the total sign‑ins for that day. After invoking the functions for two users, the script outputs the daily sign‑in total.
4. Conclusion
Redis bitmap operations provide an efficient way to achieve precise statistical calculations. By using BITSET and BITGET to manipulate individual bits and BITCOUNT to aggregate them, developers can implement features such as user sign‑in tracking with minimal storage and high performance. The PHP example illustrates how to integrate these commands into a real‑world application.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.