Redis learning notes – (1) – bitmap usage 1 – count the login days of all users in one year

Time:2022-5-26

1. Bitmap usage 1: count the login days of all users in one year

Command list:setbit getbit bitcount

Demand 1: the e-commerce website counts the login days of all users in a year. For example, if the user ID is, we want to count the login days of users every year, such as the following

user name User ID Login days of this year
Zhang San 001 100
Li Si 002 200
Wang Wu 003 365

If you use the bitmap of redis, you can do this:

setbit key offset value

setbit ulogin:001 20200101 1

  • Ulogin: 001 is the key of bitmap
  • 20200101 is offset, which records the key ID of the login value of a certain day
  • Log in as 1 on the same day, but not as 0;

Query a day:
getbit key offset

Count the of all the keys1Number of values (i.e. login days)
bitcount key

1.1 record the login operation of a day – setbit

127.0.0.1:6379> setbit ulogin:001 20200101 1
(integer) 0
127.0.0.1:6379> setbit ulogin:001 20200102 1
(integer) 0
127.0.0.1:6379> setbit ulogin:001 20200103 1
(integer) 0
127.0.0.1:6379> setbit ulogin:001 20200104 0
(integer) 0

1.2 query whether you logged in one day – getbit

127.0.0.1:6379> getbit ulogin:001 20200102
(integer) 1

1.3 how many days have the query user logged in

127.0.0.1:6379> bitcount ulogin:001
(integer) 3

If we want to count the login days of all users, we usually record them every day:

127.0.0.1:6379> setbit ulogin:002 20200101 1
(integer) 0
127.0.0.1:6379> setbit ulogin:003 20200102 1
(integer) 0

1.4 count the login days of all users

If you want to count all users, use the prefix naming rules in Javaulogin:Traverse all the in a for loopID listJust put the result of calling redis into a collection!!