Redis five data types usage scenarios

Redis is a NoSQL database based on key-value pairs. Its value is mainly composed of five basic data structures: string (string), hash (hash), list (list), set (collection), and zset (ordered collection) Composition, in addition to supporting some other data structures and algorithms. Keys are all composed of strings, so what are the usage scenarios of these five data structures? Take a look!



A string

The string type is the most basic data structure of Redis. The string type can be data such as JSON, XML or even binary images, but the maximum value cannot exceed 512MB.

1.1 Internal coding

Redis will decide which internal encoding to use according to the type and length of the current value. There are 3 types of internal codes for string types:

  1. int: 8-byte long integer.
  2. embstr: A string of 39 bytes or less.
  3. raw: string greater than 39 bytes.

1.2 Usage scenarios

1.2.1 Cache

In web services, MySQL is used as the database and Redis as the cache. Because Redis has the characteristics of supporting high concurrency, it can usually speed up reading and writing and reduce back-end pressure. Most of the requests on the web side are data obtained from Redis. If there is no required data in Redis, it will get it from MySQL and write the obtained data to redis.

1.2.2 Count

There is a string-related command incr key in Redis. The incr command performs an auto-increment operation on the value. The returned result is divided into the following three situations:

  1. Value is not an integer, return an error
  2. The value is an integer, and the result after the increment is returned
  3. key does not exist, the default key is 0, return 1

For example, the number of articles read, the number of videos played, etc. will be counted by redis. Each time it is played, the corresponding playback volume will increase by 1, and the data will be stored asynchronously in the database to achieve the purpose of persistence.

1.2.3 Shared Session

In a distributed system, each request of a user will access a different server, which will cause the problem of session synchronization. If a request to obtain user information falls on the A server, it will be stored after obtaining the user information session. The next request falls on server B. If you want to get user information from the session, you can’t get it normally, because the user information session is on server A. To solve this problem, redis is used to centrally manage these sessions and save the session to redis. , When you use it, you can get it directly from redis.

1.2.4 Speed ​​limit

For security reasons, some websites restrict IP, restricting the number of visits to the same IP within a certain period of time not to exceed n times.



Two hash

In Redis, the hash type refers to the storage structure of a key-value pair.

2.1 Internal coding

There are two types of internal coding for hash types:

  1. ziplist (compressed list): used when the number of hash type elements is less than the hash-max-ziplist-entries configuration (default 512) and all values ​​are less than the hash-max-ziplist-value configuration (default 64 bytes). Ziplist uses a more compact structure to achieve continuous storage of multiple elements, so it saves more memory than hashtable.
  2. Hashtable (hash table): When ziplist cannot meet the requirements, hashtable is used.

2.2 Usage scenarios

Since the hash type stores a key-value pair, for example, the database has the following user table structure

id name age
1 Java journey 18

Save the above information in redis:
id as the key and user attributes as the value:
hset user:1 name Java journey age 18

Using hash storage will be more convenient and intuitive than string



Three lists

The list type is used to store multiple ordered strings. A list can store up to 2^32-1 elements. Both ends of the list can insert and pop elements.

3.1 Internal coding

There are two internal codes for the list:

  1. ziplist (compressed list): used when the number of hash type elements is less than the list-max-ziplist-entries configuration (default 512) and all values ​​are less than the list-max-ziplist-value configuration (default 64 bytes). Ziplist uses a more compact structure to achieve continuous storage of multiple elements, so it saves more memory than hashtable.
  2. Linkedlist (linked list): When the ziplist cannot meet the requirements, the linkedlist will be used.

3.2 Usage scenarios

3.2.1 Message Queue

The list is used to store multiple ordered strings. Since it is ordered, it satisfies the characteristics of the message queue. Use lpush+rpop or rpush+lpop to implement message queue. In addition, redis supports blocking operations and uses blocking commands to implement blocking queues when popping elements.

3.2.2 Stack

Since the list stores ordered strings, which satisfies the characteristics of the queue, it can also meet the characteristics of the stack first in and last out. Use lpush+lpop or rpush+rpop to implement the stack.

3.2.3 Article list

Because the elements of the list are not only ordered, but also support to get elements according to the index range. So we can use the command lrange key 0 9 to page to get the list of articles



Four sets

The collection type can also store multiple string elements. Unlike lists, duplicate elements are not allowed in the collection and the elements in the collection are unordered. A collection can store up to 2^32-1 elements.

4.1 Internal coding

There are two types of internal codes for collections:

  1. intset (integer set): When the elements in the set are all integers and the number of elements is less than the set-max-intset-entries configuration (default 512), redis will use intset as the internal implementation of the set, thereby reducing memory usage .
  2. hashtable (hash table): When intset cannot meet the requirements, hashtable is used.

4.2 Usage scenarios

4.2.1 User Tag

For example, one user is interested in basketball and football, and another user is interested in football and table tennis. These points of interest are a label. With this data, people who like the same tag can be obtained, as well as tags that are of common interest to users.

When labeling users, you need to ①label users, ②add users to labels, you need to add transactions to these two operations.

User tagging
sadd user: 1: tags tag1 tag2
to the label to add a user
Sadd tag1: the Users the User: 1
Sadd tag2: the Users the User: 1

Use sinter to find the common tags of two
users sinter user:1:tags user:2:tags

4.2.2 Lottery function

The collection has two commands to support obtaining random numbers, namely:

  1. Randomly get count elements, the number of set elements remains unchanged srandmember key [count]
  2. Count elements are randomly popped, the elements are popped from the collection, and the number of collection elements changes spop key [count]

The user clicks the lottery button, the parameter draw, puts the user number into the set, and then draws the first prize and the second prize respectively. If the user who has already won the first prize cannot draw the second prize by parameter, use spop, otherwise use srandmember .



Five ordered sets

Ordered collections are the same as collections and cannot have repeated elements. But it can be sorted. It sets a score for each element as the basis for sorting. Up to 2^32-1 elements can be stored.

5.1 Internal coding

There are two types of internal codes for ordered set types:

  1. ziplist (compressed list): Used when the number of elements in an ordered set is less than the list-max-ziplist-entries configuration (128 by default) and all values ​​are less than the list-max-ziplist-value configuration (64 bytes by default). Ziplist uses a more compact structure to achieve continuous storage of multiple elements, which saves more memory.
  2. skiplist (skip list): When the ziplist requirements are not met, skiplist will be used.

5.2 Usage scenarios

5.2.1 Ranking

The user has published n articles, others will like the articles they like after seeing the articles, use score to record the number of likes, and the ordered collection will be ranked according to the score. The process is as follows:

The user publishes an article, the initial number of likes is 0, that is, the score is 0
zadd user:article 0 a
Someone likes article a, increment by 1
zincrby user:article 1 a
query like the first three articles
zrevrangebyscore user:article 0 2
Query the three articles after the
like zrangebyscore user:article 0 2

5.2.2 Delayed message queue

Order placing system, payment needs to be made within 15 minutes after placing the order, and the order will be automatically cancelled if the payment is not made within 15 minutes. The fifteen minutes after the order is placed is used as the score, the order is stored in redis as the value, and the consumer polls to consume. If the consumption is greater than or equal to the score of this record, the record is removed from the queue and the order is cancelled.



to sum up

In development, the string type is the most used data type, which leads us to ignore the other four data types of redis. Choosing specific data types in specific scenarios is very helpful to improve the performance of redis. Although redis supports the implementation of message queues, it does not support ack. Therefore, the message queue implemented by redis cannot guarantee the reliability of the message unless you implement the message confirmation mechanism yourself, but this is very troublesome, so if it is an important message, it is recommended to use a special message queue to do it.

Guess you like

Origin blog.csdn.net/QiuHaoqian/article/details/109524807