Redis data structure string

This article talks about the string of Redis data structure

Article Directory


The string type is the most basic data structure of Redis . The value of the string type can actually be a string (simple and complex string, such as JSON, XML), a number (integer, floating point), or even a binary (picture, audio, video), but the maximum value cannot exceed 512MB.

Insert picture description here

Basic command

Official website:
Chinese website:

Here are only some of the commonly used ones, please refer to the above official website for details

Insert picture description here

Related commands

Common commands


set key value [ex seconds] [px milliseconds] [nx|xx]

The set command has several options :

  1. ex seconds: Set the expiration time in seconds for the key.
  2. px milliseconds: Set the expiration time in milliseconds for the key.
  3. nx: The key must not exist before it can be set successfully and used for adding .
  4. xx: Contrary to nx, the key must exist before it can be set successfully and used for update .

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

setex key seconds value
setnx key value

setex: Set the value of the key and specify the effective time corresponding to this key value> setex hello 10 world
OK> get hello
"world"> get hello

setnx: The key must not exist before it can be set successfully. If the key already exists, 0 is returned .> set aaa bbb
OK> setnx aaa bbbb
(integer) 0> setnx aaaa bbbb
(integer) 1> get aaaa

Get value

get key

If the key to be obtained does not exist, nil (empty) is returned .> set 77 88
OK> get 77
"88"> get 88

Bulk setting values

mset key value [key value …]

The following operation uses the mset command to set 4 key-value pairs at once :> mset a 1 b 2 c 3 d 4

Get values ​​in batch

mget key [key …]

Obtain the values ​​of keys a, b, c, and d in batches by the following operations :> mget a b c d
1) "1"
2) "2"
3) "3"
4) "4">

Batch operation commands can effectively improve development efficiency. If there is no such command as mget, the process and time consumption for executing the get command n times are as follows :

n get time = n network time + n command time
Insert picture description here

After using mget command, the process and time-consuming of executing get command n times are as follows :

n get time = 1 network time + n command time
Insert picture description here

Redis can support tens of thousands of read and write operations per second, but this refers to the processing capabilities of the Redis server. For the client, a command has network time in addition to the command time.

Assuming that the network time is 1 millisecond and the command time is 0.1 millisecond (calculated based on processing 10,000 commands per second), the difference between 1000 get commands and 1 mget command is shown in the table:

1000 get operations1000 * 1 + 1000 * 0.1 = 1100ms = 1.1s
1 mget operation1 * 1 + 1000 * 0.1 = 101ms = 0.101s


incr key

The incr command is used to auto-increment the value, and the returned result is divided into three situations :

  • The value is not an integer, and an error is returned.
  • The value is an integer, and the result after self-increment is returned.
  • The key does not exist, it is incremented according to the value of 0, and the return result is 1.> set 66 77
OK> incr 66
(integer) 78> exists 22
(integer) 0> incr 22
(integer) 1>

In addition to the incr command, Redis also provides command operations such as decr (decrement), incrby (increment a specified number), decrby (decrement a specified number), incrbyfloat (increment a floating point number) :

decr key incrby key increment
decrby key decrement incrbyfloat key increment

Many storage systems and programming languages ​​internally use the CAS mechanism to implement the counting function, and there will be a certain amount of CPU overhead. But this problem does not exist in Redis at all, because Redis is a single-threaded architecture, any command must be executed sequentially when it reaches the Redis server.

Uncommon commands

Append value

append key value

append can append a value to the end of a string .> set key hello
OK> get key
"hello"> append key world
(integer) 10> get key

String length

strlen key

For example, the current value is redisworld, so the return value is 10 :> get key
"helloworld"> strlen key
(integer) 10>

Set and return to the original value

getset key value

getset and set will set the value, but the difference is that it will also return the original value of the key, for example :> getset 99 100
(nil)> getset 99 101

Set the character at the specified position

setrange key offeset value

The following operation changes the value from abcd to ebcd :> set ee abcd
OK> setrange ee 0 e
(integer) 4> get ee

Get part of the string

getrange key start end

start and end are the start and end offsets, and the offset starts from 0. For example, the command to get the first three characters of the value ebcd is as follows :> get ee
"ebcd"> getrange ee 0 2

Finally, a description of the time complexity of string type commands is given :

Insert picture description here

Typical usage scenarios

Cache function

The following is a typical cache usage scenario, where Redis is used as the cache layer and MySQL is used as the storage layer. Most of the requested data is obtained from Redis. Because Redis has the characteristics of supporting high concurrency, the cache usually plays a role in accelerating reading and writing and reducing backend pressure .

Insert picture description here
The pseudo code of the entire function is as follows
public UserInfo getUserInfo(long id) {

    String userRedisKey = "user:info:" + id;
    String value = redis.get(userRedisKey);
    UserInfo userInfo;    
    if (value != null) {
        userInfo = deserialize(value);     
    } else {        
        userInfo = mysql.get(id);   if (userInfo != null) { 
            redis.setex(userRedisKey, 3600, serialize(userInfo));
        return userInfo;

Shared Session

A distributed Web service stores the user's session information (such as user login information) in their respective servers. This will cause a problem. For the sake of load balancing, distributed services will balance the user's access to different servers. Users may find that they need to log in again after refreshing their access. This problem is intolerable to users.

Insert picture description here

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, each user updates or queries login information directly from Redis .

Insert picture description here


Many applications will use Redis as the basic tool for counting. It can realize the functions of fast counting and query caching. At the same time, data can be asynchronously landed to other data sources. Generally speaking, the video playback count system uses Redis as the basic component for counting the video playback count. Every time the user plays a video, the corresponding video playback count will increase by one .

The pseudo code of the entire function is as follows
public long incrVideoCounter (long id) {

    String key = "video:playCount:" + id;
    return redis.incr(key);
In fact, there are many issues to consider in a real counting system: anti-cheating, counting according to different dimensions, data persistence to the underlying data source, etc.

Speed ​​limit

For security reasons, many applications will ask the user to enter the mobile phone verification code every time they log in to determine whether it is the user himself. However, in order to avoid frequent access to the SMS interface, the frequency with which the user obtains the verification code every minute will be restricted. For example, no more than 5 times per minute, as shown in the figure :

This function can be implemented using Redis, the pseudo code is as follows:

String phoneNum = "138xxxxxxxx";
String key = "shortMsg:limit:" + phoneNum;
// SET key value EX 60 NX
boolean isExists = redis.set(key, 1, "EX 60", "NX");
if (isExists != null && redis.incr(key) <= 5) {
    // 通过
} else {
    // 限速

The above is the use of Redis to achieve the speed limit function. For example, some websites restrict an IP address from being accessed more than n times in a second . A similar idea can also be adopted .

This article references

"Redis Development and Operation and Maintenance"

Summary of this article

This article introduces the knowledge related to Redis strings in detail.