preface
The string type is the most fundamental data structure of Redis. String values can actually be strings (simple and complex strings, such as JSON and XML), numbers (integers, floating-point numbers), and even binary (pictures, audio, video), but cannot exceed 512MB.
Other articles
-
Redis series (1) – Redis introduction and master-slave setup
-
In-depth analysis of Redis series ii – Redis Sentinel mode and high availability cluster
-
In-depth analysis of Redis series (3) – Redis cluster mode construction and detailed explanation of the principle
-
In-depth analysis of Redis series (4) – Redis data structure and global command overview
-
An in-depth analysis of Redis series 5 – Redis data structure strings
-
In-depth analysis of Redis series (6) – Redis data structure hashing
-
An in-depth look at Redis series 7 – Redis data structure list
-
An in-depth analysis of Redis series (eight) – Redis data structure collection
The body of the
1. Related commands
1.1. Common Commands
1.1.1. Set the value
set key value [ex seconds] [px milliseconds] [nx|xx]
The set command has several options:
- Ex seconds: Sets the key expiration time in seconds.
- Px milliseconds: Sets the expiration time for the key in milliseconds.
- Nx: The key must not exist.
- xxAnd:
nx
Instead, the bond mustThere are, can be set successfullyupdate.
In addition to the set option, Redis also provides two commands: setex and setnx:
setex key seconds value setnx key value
- Setex: Sets the value of the key and specifies the time that this key value is valid.
127.0.0.1:6379> setex key1 5 value1
OK
127.0.0.1:6379> get key1
"value1"127.0.0.1:6379 > get key1 (nil)Copy the code
- setnx: a key must beThere is no“Can be set successfully. Returns if the key already exists
0
.
127.0.0.1:6379 >setKey2 value1 OK 127.0.0.1:6379> setnx key2 value2 (integer) 1
127.0.0.1:6379> get key2
"value1"
Copy the code
1.1.2. Get the value
get key
If the key to be retrieved does not exist, nil is returned.
127.0.0.1:6379 > get not_exist_key (nil)Copy the code
1.1.3. Set values in batches
mset key value [key value …]
Set four key pairs at a time using the mset command:
127.0.0.1:6379> mset a 1 b 2 c 3 d 4
OK
Copy the code
1.1.4. Batch obtaining values
mget key [key …]
Obtain the values of keys A, B, c, and D in batches by performing the following operations:
127.0.0.1:6379> mget a b c d
1) "1"
2) "2"
3) "3"
4) "4"
Copy the code
Batch operation of commands can effectively improve the development efficiency. If there is no command such as Mget, the process and time of executing the GET command for n times are as follows:
N GET times = N network times + N command times
After the mget command is used, the process and time of running the get command n times are as follows:
N GET times = 1 network time + N command time
Redis can support tens of thousands of read/write operations per second, but this refers to the processing power of the Redis server. For the client, a command has network time as well as command time.
Assume that the network time is 1 ms and the command time is 0.1 ms (10,000 commands are processed per second), then the difference between executing 1000 GET commands and one MGET command is shown in the following table:
operation | time |
---|---|
1000 GET operations | 1000 * 1 + 1000 * 0.1 = 1100ms = 1.1s |
One MGET operation | 1 * 1 + 1000 * 0.1 = 101ms = 0.101s |
1.1.5. Count
incr key
The incr command is used to increment the value automatically. The returned result can be divided into three types:
- Value is not an integer, error returned.
- The value is an integer and returns the incremented result.
- The key does not exist
0
Since the increase, returns the result is1
.
127.0.0.1:6379 > exists key (integer) 0
127.0.0.1:6379> incr key
(integer1)Copy the code
In addition to incr commands, Redis also provides decr (decr), incrby (decrby), incrByFloat (incrByFloat) and other command operations:
decr key incrby key increment decrby key decrement incrbyfloat key increment
Many storage systems and programming languages use the CAS mechanism internally to implement the counting function, which has a certain CPU overhead. In Redis, however, this problem does not exist at all, because Redis is a single-threaded architecture and any commands that reach the Redis server are executed sequentially.
1.2. Rarely used commands
1.2.1. Additional value
append key value
Append can append values to the end of a string.
127.0.0.1:6379 > get the key"redis"
127.0.0.1:6379> append key world
(integer) 10
127.0.0.1:6379> get key
"redisworld"
Copy the code
1.2.2. String Length
strlen key
For example, the current value is redisworld, so the return value is 10:
127.0.0.1:6379 > get the key"redisworld"127.0.0.1:6379 > strlen key (integer10)Copy the code
1.2.3. Set and return the original value
getset key value
Getset sets the same value as set, but it also returns the original value of the key, for example:
127.0.0.1:6379> getset hello world
(nil)
127.0.0.1:6379> getset hello redis
"world"
Copy the code
1.2.4. Sets the character at the specified position
setrange key offeset value
The following changes the value from PEST to best:
127.0.0.1:6379 >setRedis PEST OK 127.0.0.1:6379> setrange 0 b (integer) 4
127.0.0.1:6379> get redis
"best"
Copy the code
1.2.5. Get partial strings
getrange key start end
Start and end are the start and end offsets respectively, and the offsets are calculated from 0. For example, the command to obtain the first two characters of the value best is as follows:
127.0.0.1:6379> getrange redis 0 1
"be"
Copy the code
Finally, the time complexity of string commands is given:
2. Internal coding
There are three internal encodings for string types:
-
Int: a long integer of 8 bytes.
-
Embstr: contains a string of 39 bytes or less.
-
Raw: The string contains more than 39 bytes.
Redis decides which internal encoding implementation to use based on the type and length of the current value.
- Integer types
127.0.0.1:6379 >setKey 8653 OK 127.0.0.1:6379> Object Encoding key"int"
Copy the code
- The shorter string
# A string of 39 bytes or less: embstr127.0.0.1:6379 >set key "hello,world"
OK
127.0.0.1:6379> object encoding key
"embstr"
Copy the code
- A long string
# String larger than 39 bytes: RAW127.0.0.1:6379 >set key "one string greater than 39 byte........."
OK
127.0.0.1:6379> object encoding key
"raw"127.0.0.1:6379 > strlen key (integer40)Copy the code
3. Typical application scenarios
3.1. Caching
The following is a typical cache usage scenario, in which Redis serves as the cache layer and MySQL serves as the storage layer. Most of the requested data is obtained from Redis. Because Redis supports high concurrency, caching is often used to speed up reads and writes and reduce back-end stress.
The pseudocode for the whole 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));
}
returnuserInfo; }}Copy the code
3.2. The count
Many applications will use Redis as a basic tool for counting, it can achieve fast counting, query caching, and data can be asynchronously landed to other data sources. Generally speaking, the video playback number system uses Redis as the basic component of the video playback number counting. Every time the user plays a video, the corresponding video playback number will increase by 1.
public long incrVideoCounter (long id) {
String key = "video:playCount:" + id;
return redis.incr(key);
}
Copy the code
In fact, a real counting system has many issues to consider: anti-cheating, counting by different dimensions, persisting data to underlying data sources, and so on.
3.3. The sharing Session
A distributed Web service stores a user’s Session information, such as user login information, on its own server. This causes a problem. For load balancing, distributed services will balance users’ access to different servers. Users may need to log in again after refreshing the access, which is unacceptable to users.
To solve this problem, you can use Redis to centrally manage user sessions. In this mode, as long as Redis is highly available and scalable, every user updates or queries their login information directly from Redis.
3.4. The speed limit
For security reasons, many apps ask users to enter a phone verification code each time they log in to determine if they are the user. However, to prevent the SMS interface from being frequently accessed, the frequency of obtaining verification codes per minute is limited. For example, no more than 5 times per minute, as shown in the picture:
This function can be implemented using Redis with the following pseudocode:
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) {
/ / by
} else {
/ / the speed limit
}
Copy the code
The above is the use of Redis to achieve the speed limit function, for example, some websites limit an IP address can not visit more than N times in one second can also use similar ideas.
summary
This paper briefly introduces the basic command of Redis string data structure, internal coding and related application scenarios.
reference
Redis Development and Operation
Welcome to pay attention to the technical public number: Zero one Technology Stack
This account will continue to share learning materials and articles on back-end technologies, including virtual machine basics, multithreaded programming, high-performance frameworks, asynchronous, caching and messaging middleware, distributed and microservices, architecture learning and progression.