Redis communication protocol -- RESP

Redis is a CS architecture software, and the communication is generally divided into two steps (excluding pipeline and PubSub):

  1. The client (client) sends a command to the server (server)
  2. The server parses and executes the command, and returns the response result to the client

Therefore, there must be a specification for the format of the command sent by the client and the response result of the server. This specification is the communication protocol.

In Redis, the RESP (Redis Serialization Protocol) protocol is used.

RESP

  • Redis version 1.2 introduced the RESP protocol
  • Redis 2.0 version became the standard for communicating with Redis server, called RESP2
  • In Redis version 6.0, the protocol was upgraded from RESP2 to RESP3, adding more data types and supporting the new feature of 6.0 – client cache.

Although the RESP3 protocol is very strong, its compatibility with RESP2 is particularly poor, so the RESP2 protocol is still used so far.

In RESP, different data types are distinguished by the character of the first byte. Commonly used data types include 5 types:

  1. Single-line string: the first byte is '+', followed by a single-line string, ending with CRLF ("\r\n").
    For example, the server returns "OK": "+OK\r\n"

  2. Errors: The first byte is '-', the same as the single-line string format, except that the string is exception information and ends with CRLF.
    For example: "-Error message\r\n"

  3. Value: The first byte is ':', followed by a string of numeric formats, ending with CRLF.
    For example: ":10\r\n"

  4. Multi-line string: the first byte is '$', and the second is an integer of type int, indicating the length of the string. In general, it means a binary safe string, with a maximum support of 512MB, which is similar to SDS (dynamic string). Wrap the start and end of the string with CRLW.
    The second int type:
    ● If the size is 0, it means an empty string: "$0\r\n\r\n"
    ● If the size is -1, it means it does not exist: " $ -1\r\n "
    For example: $5\r\nhello\r\n $ is expressed as a multi-line string, 5 means that the length of the string is 5, and the string is included in terms of CPLW.

  5. Array: The first byte is '*', followed by the number of elements in the array, followed by elements, and the data type of the elements is not limited.

Example 1:
*3\r\n
$3\r\nset\r\n
$4\r\nname\r\n
$6\r\nHuge\r\n

Example 2:
*3\r\n
:10\r\n
$5\r\nhello\r\n
*2\r\n$3\r\nage\r\n:10\r\n

Guess you like

Origin blog.csdn.net/weixin_45970271/article/details/126165730