Home >Database >Redis >Briefly talk about GETBIT and SETBIT in Redis

Briefly talk about GETBIT and SETBIT in Redis

藏色散人
藏色散人forward
2021-09-12 16:49:172379browse

Redis is an in-memery database, and its advantages are self-evident.
You can read the introduction on the official website for details. https://redis.io

There are five main data types: strings, lists, sets, and hashes.
When I learned the common commands of strings type, I didn’t know much about the meaning of GETBIT and SETBIT, so I searched for related articles. I saw an article introducing the application of GETBIT and SETBIT, which felt very powerful. The record is as follows:

When we log in to some blog sites or video sites , websites often record whether we read a certain article or watch a certain video.

If implemented using a traditional mysql database, if there are a large number of users and there are many articles and videos, it will put a lot of pressure on the database.

It will be much simpler to use Redis's GETBIT and SETBIT.
Let’s take video as an example. We use bitmap to record whether users have watched a certain video. One video corresponds to one bitmap. For example,

key:   video:1201
value: 000000...0000

key is marked with the video English name video colon id.
value is a bitmap. One bit has two possibilities, 0 or 1. 0 means not viewed, 1 means already viewed.
The position (offset) represents the user id. For example, the 200th position represents whether the user with user_id 200 has watched the video with id 1201.

Settings

# SETBIT key offset value

SETBIT video:1201 200 1
# 上面的命令就是设置ID为200的用户,已经看过了ID为1201的视频。

Query

# GETBIT key offset
GETBIT video:1201 200
# 上面的命令就是查询ID为200的用户是否观看了ID为1201的视频

Of course, you can also correspond to a bitmap for each user. The bits in the bitmap represent whether a video has been watched.

In addition, the article will also show that the currently very popular check-in or login records can also be implemented with a similar design.
For example, use a bitmap to record the login status of all users. One bit in the bitmap represents whether a user logged in that day, 0 means not logged in, and 1 means logged in.
Generate a bitmap every day.

By counting multi-day bitmaps, operations such as counting active users can be achieved.

Recommended study: "redis tutorial"

The above is the detailed content of Briefly talk about GETBIT and SETBIT in Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete