Shock! Redis can count user data like this

Suppose that the boss puts you a request: "Little Fatty, let me count the number of active (login) users in our system in the last month.".

Those who are familiar with relational databases know that to build a user login table, one SQL query can be done.
like this:

select distinct userid from login_log 
where login_date >20201101 and log_date<20201130;

Assuming that the user login table data is extremely large, it takes up a lot of disk space, and secondly, the efficiency of such SQL queries must not be high.

You may ask, otherwise?


For this problem, Redis really has a solution. Yes, this is the order.

What does that mean?

for example:

setbit k1 1 1 
/*设置k1的第二位为1,此时k1就是 0100 0000
(此命令会以字节为单位计值,ascii码是@,使用get k1会返回@)*/
setbit k1 14 1
/*此时 k1就是 0100 0000 0000 0010,十六进制是 @\x02 */

For the problem mentioned at the beginning of the above, we can use the date as the key of Redis, sort the users and map them to each bit on the value, and then take out each day of the current month and perform an OR operation to calculate the login of the current month. The number of users, and bit computing is what computers are very good at.

Let's look at the knowledge point of Reids' bit operations.

 

Use it like this:

After the setbit operation, the value of k1 is 0100 0000, and the value of k2 is 0000 0000. After bitop and operation, the result is stored in k3. At this time, the value of k3 is 0000 0000, so the result of get k3 is \x00.

It is not difficult to understand the situation of "or operation".

Okay, back to the question mentioned at the beginning.

We have set up three keys 20201101, 20201102, 20201103 to represent the daily user login status. Each bit on the bit represents the login status of each user, and the login on the day is set to 1.

Assuming that the 20th user logs in on the first day, the first user logs in on the second day, and the first user logs in on 03, that is, 2 users log in three times. As shown below:

 In the "or operation" (de-duplication of users) on the daily login situation, store the result of the operation in the reslut variable, and then count the number of 1s in the variable.

Finally, use bitcount to calculate the number of logged-in users as 2.


to sum up

To summarize briefly, we count user logins. In addition to the traditional use of relational database queries, there is another way of thinking that is to use the key-value-based memory database Redis.

Use Redis' setbit command to use the date as the key and map each user to each bit in the value. Then use bitop to perform bit operations that computers are very good at, and finally calculate the number of bits in value 1 through bitcount, which is the number of logged-in users.

Okay, let's stop here first. If you think it is rewarding, please forward it without mercy.

Guess you like

Origin blog.csdn.net/H517604180/article/details/110728374