13
头图
This article is transferred from Redis Interview Daquan , which summarizes related interview questions such as PHP, Golang, Redis, MySQL, etc.

Talk about the current status of Redis

Redis, as an in-memory non-relational database, is almost always used in large and small Internet factories, large projects and small projects. Why is Redis so favored? Regarding this issue, many programmers may only use it while watching others, and lack a comprehensive understanding of Redis.

Redis usage scenarios

cache

Caching is now a nirvana used by almost all medium and large websites. Reasonable use of caching can not only improve website access speed, but also greatly reduce the pressure on the database. Redis provides a key expiration function and a flexible key elimination strategy. Therefore, Redis is used in many occasions for caching.

Leaderboard

Many websites have ranking applications, such as JD.com's monthly sales list, and new rankings of products by time. The ordered set data class provided by Redis can implement various complex ranking applications.

counter

What is a counter, such as the number of views of goods on e-commerce websites, the number of videos played on video websites, etc. In order to ensure the real-time effectiveness of data, +1 must be given for each browsing. When the concurrency is high, it will undoubtedly be a challenge and pressure to request database operations every time. The incr command provided by Redis to implement the counter function, memory operation, and performance is very good, which is very suitable for these counting scenarios.

Distributed session

In the cluster mode, when there are not many applications, the session replication function that comes with the container is generally sufficient. When the number of applications increases and relatively complex systems are used, a session service centered on an in-memory database such as Redis is generally built, and the session is no longer available. Managed by the container, but managed by the session service and the in-memory database.

Distributed lock

Distributed technology is used in many Internet companies. The technical challenge brought by distributed technology is concurrent access to the same resource, such as global ID, inventory reduction, spike and other scenarios. Pessimistic locks and optimistic locks are implemented, but in high concurrency situations, it is not ideal to use database locks to control concurrent access to resources, which greatly affects the performance of the database. You can use the setnx function of Redis to write distributed locks. If the setting returns 1, it means that the lock acquisition is successful, otherwise the lock acquisition fails, and more details need to be considered in practical applications.

Social network

Like, dislike, follow/be followed, mutual friends, etc. are the basic functions of social networking sites. The traffic of social networking sites is usually relatively large, and traditional relational database types are not suitable for storing this type of data. Redis provides ha Data structures such as Greek and collection can easily implement these functions.

latest list

Redis list structure, LPUSH can insert a content ID as a keyword in the head of the list, and LTRIM can be used to limit the number of lists, so that the list will always have N IDs, no need to query the latest list, and go directly to the corresponding content page according to the ID. Can.

message system

Message queue is a must-use middleware for large websites, such as ActiveMQ, RabbitMQ, Kafka and other popular message queue middleware. It is mainly used for business decoupling, traffic peak shaving and asynchronous processing of low real-time business. Redis provides publish/subscribe and blocking queue functions, which can implement a simple message queue system. In addition, this cannot be compared with professional message middleware.

how to use

Various usage scenarios are mentioned above. In these scenarios, it is nothing more than operations on Redis data types. You need to have some understanding of Redis data types. There are these data types in Redis.
String, Hash, List, Set, Zset, GEO, Stream, HyperLogLog, BitMap.

Data usage scenarios

String type

The String type is a string type, similar to a key-value pair.

Generally, we use the String type to store the number of goods, user information and distributed locks and other application scenarios.

Store the number of items.

 set goods:count:1 1233
set goods:count:2 100

User Info.

 set user:1 "{"id":1, "name":"张三", "age": 12}"
set user:2 "{"id":2, "name":"李四", "age": 12}"

Distributed lock.

 # 设置一个不存在的键名为id:1值为10, 过期时间为10秒。
127.0.0.1:6379> set id:1 10 ex 10 nx
OK
127.0.0.1:6379> get id:1
"10"
# 当前的键还未过期,在次设置则不会设置成功。
127.0.0.1:6379> set id:1 10 ex 10 nx
(nil)
# 当10秒之后去获取,当前的键则为空。
127.0.0.1:6379> get id:1
(nil)
Using Redis to implement the principle of distributed locks, when a key exists, the setting fails.

hash type

The hash type is a data structure similar to a relational database structure. There is a key name, and the content stored in the key exists in the form of key-value pairs.

Using the hash structure, we can use it to store business scenarios such as user information and object information.

save user information.

 127.0.0.1:6379> hset user:1 id 1 name zhangsan age 12 sex 1
(integer) 4
127.0.0.1:6379> hset user:2 id 2 name lisi age 14 sex 0
(integer) 4
127.0.0.1:6379> hmget user:1 id name age sex
1) "1"
2) "zhangsan"
3) "12"
4) "1"

Store object information.

 127.0.0.1:6379> hset object:user id public-1 name private-zhangsan
(integer) 2
127.0.0.1:6379> hmget object:uesr id name
1) (nil)
2) (nil)
127.0.0.1:6379> hget object:user id
"public-1"
127.0.0.1:6379>
A user object is stored here, and there are two attributes in the object, namely id and name words, which store the access rights and default values of the attributes respectively.

list type

The list type is a list-type data structure. With one key, arrange the data in order.

Lists are generally used in scenarios such as queues, stacks, and spikes.

queue.

 127.0.0.1:6379> lpush list:1 0 1 2 3 4 5 6
(integer) 7
127.0.0.1:6379> rpop list:1 1
1) "0"
127.0.0.1:6379> rpop list:1 1
1) "1"
127.0.0.1:6379> rpop list:1 1
1) "2"
The use of list to implement the queue is because the queue follows the characteristics of first-in, first-out.

stack.

 127.0.0.1:6379> lpush list:1 3 4 5 6
(integer) 3
127.0.0.1:6379> lpop list:1
"6"
127.0.0.1:6379> lpop list:1
"5"
127.0.0.1:6379> lpop list:1
"4"
127.0.0.1:6379> lpop list:1
"3"
The use of list to implement queues is because queues follow the characteristics of last-in, first-out.

Spike.

 127.0.0.1:6379> lpush order:user 11 12 14 15 16 17
(integer) 6
In the seckill scenario, we can write the successful seckill users into the queue first, and the subsequent business is processed according to the data in the queue.

set type

zet is a collection type, and the elements within such a collection are unnecessary and non-repeating.

The set type can generally be used in business scenarios such as user check-in, website visit statistics, user attention tags, friend recommendation, prize guessing, and random number generation.

User sign-in status on a certain day.

 127.0.0.1:6379> sadd sign:2020-01-16 1 2 3 4 5 6 7 8
(integer) 8
127.0.0.1:6379> smembers sign:2020-01-16
1) "1"
2) "2"
3) "3"
4) "4"
5) "5"
6) "6"
7) "7"
8) "8"
The key is a specific day, and the stored value is the id of the logged-in user.

User follows tags.

 127.0.0.1:6379> sadd user:1:friend 1 2 3 4 5 6
(integer) 6
127.0.0.1:6379> sadd user:2:friend 11 22 7 4 5 6
(integer) 6
127.0.0.1:6379> sinterstore user:relation user:1:friend user:2:friend
(integer) 3
127.0.0.1:6379> smembers user:relation
1) "4"
2) "5"
3) "6"
User 1 follows the columns with ids 1, 2, 3, 4, 5, and 6. User 2 follows the columns with ids 11, 22, 7, 4, 5, and 6. Here are the columns that two users are concerned about together.

Guess the prize.

 127.0.0.1:6379> spop user:2:friend 1
1) "5"
The use of set to realize the guessing award mainly uses the characteristics of randomly throwing elements of the set class.

zset type

Both the zset type and the set type belong to the collection type. The difference between the two is that a score should be set when setting the zset data. This score can be used for data sorting, and the data of the zset type is ordered, so zset is also called. ordered collection.

In addition to being used in scenarios where set is available, zset can also be used in sorting scenarios, such as leaderboards and delay queues, such as how long an unpaid order will expire.

Sign in to the leaderboard.

 127.0.0.1:6379> zadd goods:order 1610812987 1
(integer) 1
127.0.0.1:6379> zadd goods:order 1610812980 2
(integer) 1
127.0.0.1:6379> zadd goods:order 1610812950 3
(integer) 1
127.0.0.1:6379> zadd goods:order 1610814950 4
(integer) 1
127.0.0.1:6379> zcard goods:order
(integer) 4
127.0.0.1:6379> zrangebyscore goods:order 1610812950 1610812987
1) "3"
2) "2"
3) "1"
Use the user's check-in time as the ranking score, and finally query the id of the check-in user within the specified range.

Bitmaps type

The underlying storage of Bitmaps is data in a binary format. In some specific scenarios, using this type can greatly reduce the storage space , because the stored data can only be 0 and 1. For ease of understanding, this data format can be understood as being stored in the form of an array.

Using this feature, this type can be used in some access statistics, check-in statistics and other scenarios.

One month's check-in record of a user.

 127.0.0.1:6379> setbit user:2020-01 0 1
(integer) 0
127.0.0.1:6379> setbit user:2020-01 1 1
(integer) 0
127.0.0.1:6379> setbit user:2020-01 2 1
(integer) 0
127.0.0.1:6379> bitcount user:2020-01 0 4
(integer) 3
Statistics show that the user only has 4 days to sign in this month.

Count the number of check-ins on a website on a given day.

 127.0.0.1:6379> setbit site:2020-01-17 1 1
(integer) 0
127.0.0.1:6379> setbit site:2020-01-17 3 1
(integer) 0
127.0.0.1:6379> setbit site:2020-01-17 4 1
(integer) 0
127.0.0.1:6379> setbit site:2020-01-17 6 1
(integer) 0
127.0.0.1:6379> bitcount site:2020-01-17 0 100
(integer) 4
127.0.0.1:6379> getbit site:2020-01-17 5
(integer) 0
Here, the user's id is used as the offset, and the check-in is 1. The total number of specific visits can be counted, and at the same time, it can be queried based on the id of a user whether he is currently checking in. If a value is repeatedly set according to the offset, it will not be added repeatedly at this time, but Redis will return 1 to indicate that it currently exists.

Calculate the number of users who have signed in within a certain period of time.

 127.0.0.1:6379> setbit site:2020-01-18 6 1
(integer) 0
127.0.0.1:6379> setbit site:2020-01-18 4 1
(integer) 0
127.0.0.1:6379> setbit site:2020-01-18 7 1
(integer) 0
127.0.0.1:6379> bitop and continue:site site:2020-01-18 site:2020-01-17
(integer) 1
This scenario is used because this data type can compute the intersection (and) of multiple keys. At the same time can take the union (or), or (or), exclusive or (xor).

HypefLogLog type

The HypefLogLog type is somewhat similar to the collection type in terms of use. The type is actually a data structure of type string. The biggest advantage of using this type is to reduce space, but there is also a certain error rate. This type also does not allow duplicate elements for the same key. This type also supports combining the values of multiple keys.

This data type is generally used in some statistical scenarios that do not require accurate calculation.

User check-in statistics.

 127.0.0.1:6379> pfadd 2020:01:sgin  1 2 3 4 5 6 7 8
(integer) 1
# 尝试重复添加
127.0.0.1:6379> pfadd 2020:02:sgin  1 2 3 4 5 6 7 8
(integer) 0
127.0.0.1:6379> pfadd 2020:02:sgin  9
(integer) 1
127.0.0.1:6379> pfadd 2020:02:sgin  10
(integer) 1
127.0.0.1:6379> pfadd 2020:02:sgin  11
(integer) 1
127.0.0.1:6379> pfcount 2020:02:sgin
(integer) 11

GEO type

GEO type is a data format for storing geographic information, based on the data characteristics. It can be used in some business scenarios such as distance calculation and nearby recommendation.

distance calculation

 127.0.0.1:6379> geoadd city:distance nx 121.32 42.36 beijing 121.20 38.56 
shanghai 100.36 38.56 sichuan
(integer) 3
127.0.0.1:6379> geopos city:distance beijing shanghai sichuan
1) 1) "121.32000178098678589"
   2) "42.36000020595371751"
2) 1) "121.19999974966049194"
   2) "38.55999947301710762"
3) 1) "100.3599974513053894"
   2) "38.55999947301710762"
# 计算出北京到上海的距离
127.0.0.1:6379> geodist city:distance beijing shanghai km
"422.7819"

Stream type

The Stream type is a data structure added to Redis after version 5.0. This data structure is mainly used for the scenario of user message queue. Redis itself has a Redis publish and subscribe (pub/sub) to realize the function of message queue, but it has the disadvantage that the message cannot be persisted. If there is a network disconnection, Redis downtime, etc., the message will be discarded.

message queue

 # 添加消息队列
127.0.0.1:6379> xadd message * name zhangsan age 12
"1610873104343-0"
127.0.0.1:6379> xrange message - +
1) 1) "1610873104343-0"
   2) 1) "name"
      2) "zhangsan"
      3) "age"
      4) "12"
# 获取消息队列
127.0.0.1:6379> xrevrange message + - count 1
1) 1) "1610873104343-0"
   2) 1) "name"
      2) "zhangsan"
      3) "age"
      4) "12"

Mandy
412 声望627 粉丝