In my work these days, I came across a case that I needed to realize an IM online user status record by myself. At that time, I checked a lot of implementation methods, and today I will share them
The main idea
Create a bitmap that stores binary data, such as: 1 0 1 0 1 0 1 0 1, modify the user online status by changing the 0 and 1 in the corresponding position of userId. Since the default value is 0, 1 represents the user is online and 0 represents the user is offline, as shown in the figure:
Three bitmaps are constructed: Mon, Thus, and Web. For Mon, the user with userId=1 is online, the user with userId=2 is offline, and the user with userId=3 is online. When the user with userId=10 is online, the value of the 10th bit is changed to 1
Space forecast
A bit of binary data is 1bit
1 Gigabyte (GB)=8589934592 bits (bit)
In theory, 1 gb of memory can record more than 8.5 billion user states. If userIDS are incoherent, some userIDS have more than 8.5 billion bits, you can use some algorithms or segment userids by bit to solve the problem
Using the command
Setbit key offset value Changes the value of offset in the key to value
Getbit key offset Obtains the value of the offset bit in the key
Bitcount Key Indicates the number of 1s in the key
Bitop op destKey key1 key2… . Where op can be AND (OR), OR (OR), NOT (NOT), OR (XOR)
The key1, key2… And so on, such binary data, logical operation by bit, the result is paid to the destkey, there is no setbit position is 0 by default
Take a chestnut
Three bitmaps, Mon, Thus and Web, are constructed as bitmaps of the login status in the last three days
The first day
The user with userId=10000, userId=9999, userId=8888 is logged in
setbit mon 10000 1;
setbit mon 9999 1;
setbit mon 8888 1;
Copy the code
Collect the number of online users on day 1
bitcount mon
Copy the code
Three users logged in on the first day
The second day
The user userId=9999,userId=7777 is logged in
setbit thus 9999 1;
setbit thus 7777 1;
Copy the code
Obtain the online status of user userId=7777
getbit thus 7777
Copy the code
On the third day
The user userId=9999, userId=6666 is logged in
setbit web 9999 1;
setbit web 6666 1;
Copy the code
Get the number of users who have logged in for three days
bitop and resultand mon thus web;
Copy the code
Get the number of users logged in within three days
bitop or resultor mon thus web;
Copy the code
Redis uses bitmap to record the status of online users for everyone here, welcome everyone to communicate, point out some mistakes in the article, let me deepen my understanding.
Thank you!