What are the common data structures of Redis and how to implement them

01-12-2023

This article mainly introduces what are the commonly used data structures of Redis and how to implement them. In daily operations, I believe many people have doubts about what are the commonly used data structures of Redis and how to implement them. Here is a simple and easy-to-use operation method, and I hope it will help you to answer your doubts about the common data structures of Redis and how to implement them! Next, please follow the editor to learn together!

Redis common data structure

Redis provides some data structures for us to access data in Redis, the most commonly used are 5 kinds, String (String), hash (Hash), list (list), set (set), ordered set (ZSET).

String (String)

The string type is the most basic data structure of Redis. First of all, the keys are all string types, and several other data structures are built on the basis of string types, so the string type can lay the foundation for the learning of the other four data structures. The value of the string type can actually be a string (simple string, complex string (such as JSON, XML)), number (integer, floating point number), or even binary (picture, audio, video), but the maximum value Cannot exceed 512MB.

(Although Redis is written in C, there are strings in C, but due to various considerations, Redis still implements the string type by itself)

Operation command
set setting value

set key value

The set command has several options:

ex seconds: Set the second-level expiration time for the key.

px milliseconds: Set the millisecond expiration time for the key.

nx: The key must not exist before it can be set successfully for adding (commonly used for distributed locks).

xx: Contrary to nx, the key must exist before it can be successfully set and used for update.

213.jpg

From the perspective of execution effect, the ex parameter is basically the same as the expire command. Another thing that needs special attention is that if a string has an expiration time set, and then you call the set method to modify it, its expiration time will disappear.

The execution effects of nx and xx are as follows

1.jpg

In addition to the set option,Redis also provides two commands setex and setnx:

setex key seconds value

setnx key value

setex and setnx have the same function as ex and nx options. That is, setex sets the second-level expiration time for the key, and the key must not exist when setnx is set, so that the setting can be successful.


Because the key foo-ex already exists, so setnx fails, the return result is 0, the key foo-ex2 does not exist, so setnx succeeds, the return result is 1.

Is there any application scenario? Take the setnx command as an example. Due to the single-threaded command processing mechanism of Redis, if multiple clients execute setnx key value at the same time, only one client can set the value according to the characteristics of setnx Successfully, setnx can be used as an implementation of distributed locks. Of course, there is no distributed lock, not only one command is OK, there are still many things to pay attention to, we will use a separate chapter to describe the distributed lock based on Redis later.

get get value

If the key to get does not exist, it will return nil (empty):

mset batch setting values

Set 4 key-value pairs at one time through the mset command

mget Get values in batches


Get in batches The value of the key a, b, c, d:

If some key does not exist, then its value is nil (empty), and the result is returned in the order of the incoming keys.

Batch operation commands can effectively improve efficiency. If there is no such command as mget, the specific time-consuming to execute n get commands is as follows:

n get time=n network time+ n times of command time

After using the mget command, the specific time-consuming to execute n times of get command operation is as follows:

n times of get time=1 time of network time+n times of command time< /p>

Redis can support tens of thousands of read and write operations per second, but this refers to the processing capacity of the Redis server. For the client, a command has network time in addition to the command time. Assume that the network time is 1 milliseconds, the command time is 0.1 milliseconds (according to the processing of 10,000 items per secondcommand), then it takes 1.1 seconds to execute 1000 get commands (10001+10000.1=1100ms), and 1 mget command takes 0.101 seconds (11+1000 0.1=101ms).

Incr digital operation

The incr command is used to perform self-increment operations on values, and the returned results are divided into three cases:

value is not an integer, returns an error.

The value is an integer, and the result after the increment is returned.

If the key does not exist, it will be incremented according to the value of 0, and the returned result will be 1.


In addition to the incr command, Redis provides decr (self-decrement), incrby (auto-increment specified number), decrby (self-decrement specified number), incrbyfloat (self-increment floating point number) , the specific effect please students to try.

append append instruction

append can append value to the end of the string

strlen string length

return string length


Note: Each Chinese character occupies 3 bytes

getset sets and returns the original value

getset is the same as set Will set the value, but the difference is that it will return the original value of the key at the same time

setrange sets the character at the specified position< /strong>

The index starts from 0.

getrange intercepts a string

getrange intercepts a part of a string to form a substring, which needs to specify the beginning and the end offset, the intercepted range is a closed interval.

Time complexity of the command

In these commands, except del , mset, mget support batch operation of multiple keys, the time complexity is related to the number of keys, it is O(n), getrange is related to the length of the string, also O(n), other commandsThe time complexity is basically O(1), and it is still very fast in speed.

Usage scenarios

The string type has a wide range of usage scenarios:

Caching function

Redis is used as the cache layer, and MySQL is used as the storage layer. Most of the requested data is obtained from Redis. Since Redis has the feature of supporting high concurrency, the cache can usually play a role in speeding up reading and writing and reducing the pressure on the backend.

Counting

Using Redis as the basic tool for counting, it can realize the functions of fast counting and query cache, and data can be asynchronously landed to other data sources .

Shared Session

A distributed web service saves the user's Session information (such as user login information) in its own server, which will cause a problem , for the sake of load balancing, the distributed service will balance the user's access to different servers. The user may find that he needs to log in again after refreshing the access. This problem is intolerable to the user.

In order to solve this problem, you can use Redis to centrally manage the user's Session. In this mode, as long as Redis is highly available and scalable, every time the user updates or queries the login information, it will be directly Get it centrally from Redis.

Speed limit

For example, many applications will ask the user to enter the mobile phone verification code every time they log in for security reasons, so as to determine Whether it is the user himself. However, in order to avoid frequent access to the SMS interface, the frequency of obtaining verification codes per minute will be limited, for example, no more than 5 times per minute. Some websites limit that an IP address cannot be asked more than n times within one second, and a similar idea can also be adopted.

Hash (Hash)

HashMap is provided in Java, and there is a similar data structure in Redis, which is Hash type. But it should be noted that the mapping relationship in the hash type is called field-value. Note that the value here refers to the value corresponding to the field, not the value corresponding to the key.

Operation commands

Basically, the hash operation commands are very similar to the string operation commands, and many commands are in the string type commands The letter h is added in front of it, which means that the operation hash type is used, and the value of the field to be operated should also be specified.

hset setting

hset user:1 name lijin


If the setting is successful Returns 1, otherwise returns 0. In addition, Redis provides the hsetnx command, and their relationship is just like the set and setnx commands, except that the scope changes from key to field.

hget value

hget user:1 name

If the key or field does not exist, nil will be returned.


hdel deletes fields

hdel will delete one or more fields, and the returned result is the number of successfully deleted fields number.

hlen calculates the number of fields
hmset batch value
hmget batch value
hexists judge whether the field exists

If it exists, return 1, if it does not exist, return 0

hkeys Get all fields

It returns all fields for the specified hash key


hvals Get all values


hgetall gets all fields and values


When using hgetall, if the number of hash elements is compared If there are many, there will be a possibility of blocking Redis. If you only need to get some fields, you can use hmget. If you must get all field-values, you can use the hscan command, which will traverse the hash type progressively. hscan will be introduced in the following chapters.

hincrby increases

hincrby and hincrbyfloat, just like the incrby and incrbyfloat commands, but their scope is filed.

hstrlen calculates the string length of value
command time complexity

Hash type In the operation command, the time complexity of hdel, hmget, hmset is related to the number of fields in the command O(k), hkeys, hgetall, hvals are related to the total number of stored fields, O(N). The rest of the commands The time complexity is O(1).

Usage scenarios

As can be seen from the previous operations, the operations of String and Hash are very similar , Then why do you need to get a hash to store it.

The hash type is more suitable for storing object-type data. We can compare it. If the table record user in the database is:

idnameage
1lijin18
2msb20


Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us