21 How Does Redis Proceed With Protocol Parsing and Processing After Reading Request Data

21 How Does Redis Proceed with Protocol Parsing and Processing After Reading Request Data #

Hello, I am your cache course teacher, Chen Bo. Welcome to Lesson 21: “Redis Protocol Parsing and Processing”. In the previous lesson, we learned about the Redis event-driven model. Next, let’s take a look at how Redis parses and processes protocols.

Redis Protocol Parsing and Processing #

Protocol Parsing #

As mentioned in the previous lesson, when a request command enters and triggers an IO read event, the client reads the request from the connection file descriptor and stores it in the client’s query buffer. The client’s read buffer is default to 16KB. When reading a command, if it exceeds 1GB, an exception is thrown and the connection is closed.

img

After the client finishes reading the request command, it performs protocol parsing based on the query buffer. During protocol parsing, the first character of the protocol is checked. If it is “*”, it is parsed as a bulk array type, also known as MULTIBULK. Otherwise, the request is parsed as INLINE.

INLINE is a single-line string ending with CRLF, where protocol commands and arguments are separated by spaces. The parsing process follows the corresponding protocol format analyzed in the previous lessons. After protocol parsing, the number of request arguments is stored in the client’s argc, and the specific arguments of the request are stored in the client’s argv.

Protocol Execution #

After parsing the request command, it enters the protocol execution phase. In the protocol execution, for the quit command, it directly returns OK and sets the flag to close the connection after the reply.

img

For commands other than quit, the command name is taken from argv[0] in the client, and the corresponding redisCommand is searched in the server’s command table. If no redisCommand is found, an unknown command exception is returned. If a command is found, the execution starts with the proc function in the redisCommand, which executes the specific command. After the command execution is completed, the response is written to the client’s write buffer. Depending on the configuration and deployment, the write instructions are dispatched to AOF (Append Only File) and slaves. At the same time, the related statistics values are updated.