Redis Communication Protocol (protocol) _redis

Source: Internet
Author: User
Tags redis redis server
Redis Communication Protocol (protocol)

This document is translated from: Http://redis.io/topics/protocol.

The Redis protocol compromises between the following three goals: ease of implementation can be efficiently analyzed by computer (parse) can easily be read by humans to understand the network layer

The client and server use TCP connections for data interaction, with the server default port number of 6379.

All commands or data sent by the client and server end with \ r \ n (CRLF). Request

The Redis server accepts commands and the parameters of the command.

After the command is received, the server processes the command and transmits the command's reply back to the client. New Unified Request Protocol

The new version of the unified Request Protocol was introduced in Redis 1.2 and eventually became the standard way of Redis server communication in Redis 2.0.

Your Redis client should follow this new protocol for implementation.

In this protocol, all parameters sent to the Redis server are binary security (binary safe).

The following is the general form of this Agreement:

*< parameter number > CR LF
$< parameter 1 bytes number > CR LF
< parameter 1 data > CR LF
...
$< parameter N bytes number > CR LF
< parameter n data > CR LF

The command itself is also sent as one of the parameters of the protocol.

For example, the following is a printed version of a command protocol:

*3
$
SET
$
mykey
$
myvalue

The actual protocol values for this command are as follows:

"*3\r\n$3\r\nset\r\n$5\r\nmykey\r\n$7\r\nmyvalue\r\n"

As we'll see later, this format is used in the command's reply protocol in addition to the command request protocol: This reply format with only one parameter is called a bulk reply (Bulk Reply).

A unified protocol request was originally used in the reply protocol to return multiple items of a list to the client, which is referred to as multiple batch replies (Multi Bulk Reply).

A multiple batch reply is prefixed with *<argc>\r\n, followed by a number of different batch replies, where argc is the number of these batch replies. Reply

The Redis command returns many different types of replies.

By checking the first byte that the server sends back the data, you can determine what type of response it is: the first byte of the "+" error reply (Error reply) is the first byte of the "-" Integer reply (integer reply) that is the first byte of the reply (status reply) is The first byte of the bulk reply (bulk Reply) is "$" multiple bulk replies (multi Bulk Reply) The first byte is "*" Status reply

A status reply (or a single-line reply, single line reply) is a line string that ends with "+", "\ r \ n".

Here is an example of a status reply:

+ok

The client library should return all content after the "+" number. For example, in the above example, the client should return the string "OK".

State replies are usually returned by commands that do not need to return data, which is not binary safe and cannot contain new rows.

The extra overhead of a state reply is very small, requiring only three bytes (the beginning of "+" and the end of CRLF). Error reply

The only difference between the error reply and the status reply is that the first byte of the error reply is "-" and the first byte of the state reply is "+".

An error reply is sent only when a problem occurs in some places: for example, when a user executes a command on an incorrect data type, or executes a command that does not exist, and so on.

A client library should produce an exception when an error response is received.

Here are two examples of error responses:

-err unknown command ' foobar '
-wrongtype Operation against a key holding the wrong kind of value

After "-", the middle content represents the type of the error returned until the first space or new row is encountered.

ERR is a common error, and Wrongtype is a more specific error. A client implementation can produce different types of exceptions for different types of errors, or it provides a common way for callers to catch (trap) different errors by providing an error name in the form of a string.

However, these features are not used very much, so it is not particularly important that a restricted (limited) client can represent a common error condition by simply returning a logical false (false). Integer reply

An integer reply is an integer that is represented by a string that begins with ":" and ends with a CRLF.

For example, ": 0\r\n" and ": 1000\r\n" are integer replies.

The two commands that return an integer reply are INCR and lastsave. The returned integer has no special meaning, INCR returns an integer value of the key, while Lastsave returns a UNIX timestamp, the only limitation of the return value is that the number must be able to be represented by a 64-bit signed integer.

Integer replies are also widely used to represent logical true and logical false: for example, EXISTS and Sismember both use a return value of 1 to represent true, and 0 to represent false.

Other commands, such as Sadd, Srem, and Setnx, only return 1 if the operation is actually executed, or return 0.

The following command returns an integer reply: setnx, DEL, EXISTS, INCR, Incrby, DECR, Decrby, Dbsize, Lastsave, Renamenx, move, Llen, Sadd, SRE M, Sismember, SCard. Bulk reply

The server uses a bulk reply to return a binary secure string with a maximum length of MB.

Client: Get MyKey
server: Foobar

What the server sends: the first byte is the "$" symbol followed by a numeric value representing the actual reply length followed by a CRLF and followed by the actual reply data at the end is another CRLF

For the previous get command, the server actually sends the following:

"$6\r\nfoobar\r\n"

If the requested value does not exist, then the bulk reply uses the special value-1 as the length value of the reply, like this:

Client: Get non-existing-key
server: $-1

This reply is called an empty bulk reply (null Bulk Reply).

When the request object does not exist, the client should return an empty object instead of an empty string: for example, Ruby libraries should return nil, and the C library should return null (or set a special flag in the Reply object), and so on. Multiple Batch Reply

Commands like Lrange need to return multiple values, a goal that can be done with multiple batches of replies.

Multiple bulk replies are arrays of multiple replies, each element of which can be any type of reply, including multiple bulk replies per piece.

The first byte of multiple batch replies is "*" followed by a string representation of an integer value that records the number of responses contained in multiple batch replies, followed by a CRLF.

Client: Lrange mylist 0 3
server: *4
Server: $ $ server: Foo server:
$ server
: Bar
Server: $ server:
Hello
Server: $
Server: World

In the example above, all the strings sent by the server end up with CRLF.

As you can see, multiple bulk replies use the same format as the uniform request protocol used by the client when sending commands. The only difference between them is that the unified request protocol sends only bulk replies. Multiple bulk replies sent when the server answers the command can contain any type of reply.

The following example shows a multiple batch reply that contains four integer values and a binary security string:

*5\r\n
: 1\r\n:
2\r\n:
3\r\n
:
4\r\n $6\r\n foobar\r\n

In the first line of the reply, the server sends the *5\r\n, indicating that this multiple batch reply contains 5 replies, followed by the 5 reply's body.

Multiple bulk replies can also be blank (empty), just like this:

Client: Lrange nokey 0 1
server: *0\r\n

Multiple bulk replies without content (Null Multi bulk Reply) are also present, such as when the Blpop command's blocking time exceeds the maximum time limit, it returns a multiple batch reply with no content, and the counter value of this reply is-1:

Client: Blpop key 1
server: *-1\r\n

The client library should differentiate between blank multiple replies and no content multiple replies: When Redis returns a content-free reply, the client library should return a null object instead of an empty array. Empty elements in multiple bulk replies

Elements in multiple bulk replies can set their own length to-1, which means that the element does not exist and is not a blank string (empty string).

When the SORT command operates on a nonexistent key using the Get-pattern option, a number of empty elements in the batch reply occurs.

The following example shows a multiple-volume reply that contains an empty element:

Server: *3
Server: $
Server: Foo server:
$-1
Server: $
Server: Bar

Where the second element in the reply is empty.

For this reply, the client library should return a reply similar to this:

["foo", Nil, "bar"]
Multi-command and assembly line

The client can send multiple commands in a single write operation through the assembly line: You do not need to read the reply to the previous command before sending a new command. Replies to multiple commands will be returned at the end. inline command

When you need to communicate with a Redis server, but you can't find redis-cli, and only telnet, you can send commands by redis the inline command format specifically for this situation.

Here's an example of an interaction between a client and a server using inline commands:

Client: PING
server: +pong

The following is another example of an inline command that returns an integer value:

Client: EXISTS somekey
server:: 0

Because there is no "*" entry in the unified request protocol to declare the number of parameters, so when you enter commands in a Telnet session, you must use a space to split each parameter, and the server, after receiving the data, will parse the user's input by Space (parse) and obtain the command parameters. High Performance Redis Protocol analyzer

Although the Redis protocol is very useful for human reading, the definition is simple, but the implementation of this Protocol can still be as fast as the binary protocol.

Because the Redis protocol places the length of the data before the body of the data, the program does not have to scan the entire payload for a particular character, as JSON does, without escaping the payload that is sent to the server (quote).

The program can look up CR characters while processing each character in the protocol text, and calculate the length of a batch reply or multiple batch reply, like this:

#include <stdio.h>

int main (void) {
    unsigned char *p = "$123\r\n";
    int len = 0;

    p++;
    while (*p!= ' \ r ') {
        len = (len*10) + (*p-' 0 ');
        p++;
    }

    /* Now P points at ' \ R ', and the Len is in Bulk_len. *
    /printf ("%d\n", Len);
    return 0;
}

After the length of the batch reply or multiple batch reply is obtained, the program only needs to call the Read function once, and it can read all the body data of the reply into memory without any processing of the data.

The CR and LF at the end of the reply are not processed and discarded.

The implementation performance of the Redis protocol can be comparable to the performance of the binary protocol, and because of the simplicity of the Redis protocol, most advanced languages can easily implement this protocol, which makes the number of bugs in the client software greatly reduced.


From:http://redisdoc.com/topic/protocol.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.