Redis data structure string

This article talks about the string of Redis data structure

Article Directory


Overview

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: https://redis.io/commands#string
Chinese website: http://www.redis.cn/commands.html#string

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

Settings

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

127.0.0.1:6379> setex hello 10 world
OK
127.0.0.1:6379> get hello
"world"
127.0.0.1:6379> get hello
(nil)

setnx: The key must not exist before it can be set successfully. If the key already exists, 0 is returned .

127.0.0.1:6379> set aaa bbb
OK
127.0.0.1:6379> setnx aaa bbbb
(integer) 0
127.0.0.1:6379> setnx aaaa bbbb
(integer) 1
127.0.0.1:6379> get aaaa
"bbbb"
127.0.0.1:6379>

Get value

get key

If the key to be obtained does not exist, nil (empty) is returned .

127.0.0.1:6379> set 77 88
OK
127.0.0.1:6379> get 77
"88"
127.0.0.1:6379> get 88
(nil)

Bulk setting values

mset key value [key value …]

The following operation uses the mset command to set 4 key-value pairs at once :

127.0.0.1:6379> mset a 1 b 2 c 3 d 4
OK

Get values ​​in batch

mget key [key …]

Obtain the values ​​of keys a, b, c, and d in batches by the following operations :

127.0.0.1:6379> mget a b c d
1) "1"
2) "2"
3) "3"
4) "4"
127.0.0.1:6379>

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:

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

count

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.
127.0.0.1:6379> set 66 77
OK
127.0.0.1:6379> incr 66
(integer) 78
127.0.0.1:6379> exists 22
(integer) 0
127.0.0.1:6379> incr 22
(integer) 1
127.0.0.1:6379>

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 .

127.0.0.1:6379> set key hello
OK
127.0.0.1:6379> get key
"hello"
127.0.0.1:6379> append key world
(integer) 10
127.0.0.1:6379> get key
"helloworld"
127.0.0.1:6379>

String length

strlen key

For example, the current value is redisworld, so the return value is 10 :

127.0.0.1:6379> get key
"helloworld"
127.0.0.1:6379> strlen key
(integer) 10
127.0.0.1:6379>

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 :

127.0.0.1:6379> getset 99 100
(nil)
127.0.0.1:6379> getset 99 101
"100"
127.0.0.1:6379>

Set the character at the specified position

setrange key offeset value

The following operation changes the value from abcd to ebcd :

127.0.0.1:6379> set ee abcd
OK
127.0.0.1:6379> setrange ee 0 e
(integer) 4
127.0.0.1:6379> get ee
"ebcd"
127.0.0.1:6379>

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 :

127.0.0.1:6379> get ee
"ebcd"
127.0.0.1:6379> getrange ee 0 2
"ebc"
127.0.0.1:6379>

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

counter

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.