Use redistemplate to operate bitmap to complete daily check-in

Time:2021-10-22

Use redistemplate to operate bitmap to complete daily check-in

There are only two statuses: Yes and no (1, 0). A month can last up to 31 days. The four byte32 bits can just accommodate the data volume of a month. Each bit 0 and 1 indicates whether to check in or not. Therefore, using 4 bytes can represent a person’s check-in status for one month

Use redistemplate to operate bitmap to complete daily check-in

Redis BITMAP

SETBIT

Redis command: setbit key offset value

Instruction:SETBIT mykey 7 1

After using the above command, the bitmap is as follows:

Use redistemplate to operate bitmap to complete daily check-in

Java code:

Use redistemplate to operate bitmap to complete daily check-in

GETBIT

After signing in with the setbit instruction, you can use the getbit instruction if you want to get the user‘s sign in status of the current day.

Redis command: getbit key offset

Instruction:GETBIT mykey 7

1

Therefore, when the monthly check-in function is implemented, the offset can be controlled according to the date of the day, and the user check-in value is 1.

Java code:

Use redistemplate to operate bitmap to complete daily check-in

Using the get instruction, you can get the value of the whole bitmap.

Instruction:GET mykey

“x01”

BITCOUNT

If you want to get the check-in times of the user in the current month, you can use the bitcount command.

Redis command: bit count key [start end]

Gets the number of 1 in the bitmap.

Instruction:BITCOUNT mykey

1

Redistemplate does not provide a direct method to call bitcount. You can useredisTemplate.executeTo execute the bitcount method.

Java code:

Use redistemplate to operate bitmap to complete daily check-in

BITFIELD

In order to promote the continuous check-in of users, some additional rewards are sometimes given to the users who check-in continuously. At this time, it is necessary to use bitfield to judge how many days the users have checked in continuously.

The bitfield instruction executed by java code:

Use redistemplate to operate bitmap to complete daily check-in

After obtaining the return value, judge the continuous check-in times of the user in the current month:

Use redistemplate to operate bitmap to complete daily check-in

Get user check-in calendar:
Use redistemplate to operate bitmap to complete daily check-in

The above methods can meet the needs of users to sign in by natural month.

Divergence

If the requirement is 30 consecutive days from the user’s first check-in, how should it be designed?

If it is designed according to the natural week, how should it be designed?

If it is 7 consecutive days after the user’s first check-in, how can it be realized?