RESP can serialize different data types like integers, strings, arrays. There is also a specific type for errors. Requests are sent from the client to the Redis server as arrays of strings representing the arguments of the command to execute. Redis replies with a command-specific data type.
RESP is binary-safe and does not require processing of bulk data transferred from one process to another, because it uses prefixed-length to transfer bulk data.
Note: the protocol outlined here is only used for client-server communication. Redis Cluster uses a different binary protocol in order to exchange messages between nodes.
譯:
redis客戶端和redis服務端用一種名叫RESP(REdis Serialization Protocol)的協議通信。雖然這種協議專門為redis設計,但是它能被用於其它基於C/S模型的軟件項目中。
RESP是基於下面一些事實的一種折衷方案:
易於實現快速解釋人類可讀RESP能序列化不同的數據類型,例如整型,字符串,數組,還有專門的錯誤類型。客戶端發送字符串數組請求到服務端,而字符串數組表示命令參數去執行。Redis會用專門的命令類型回復。
RESP是二進制安全的,同時過程轉換中不需要大量的數據處理,因為它使用了前綴長度去轉換批量數據。
注意:在這裡概述的協議只用於客戶端-服務端通信。而Redis集群為了不同節點交換消息使用了一種不同的二進制協議。
RESP is actually a serialization protocol that supports the following data types: Simple Strings, Errors, Integers, Bulk Strings and Arrays.
The way RESP is used in Redis as a request-response protocol is the following:
Clients send commands to a Redis server as a RESP Array of Bulk Strings.The server replies with one of the RESP types according to the command implementation.In RESP, the type of some data depends on the first byte:
For Simple Strings the first byte of the reply is "+"For Errors the first byte of the reply is "-"For Integers the first byte of the reply is ":"For Bulk Strings the first byte of the reply is "$"For Arrays the first byte of the reply is "*"Additionally RESP is able to represent a Null value using a special variation of Bulk Strings or Array as specified later.
In RESP different parts of the protocol are always terminated with "\r\n" (CRLF).
譯:
RESP實際上是一種支持下面數據類型的序列化協議:短字符串,錯誤,整數,長字符串和數組。
RESP作為一種請求-回應協議,在Redis中的使用方法如下:
客戶端發送一種猶如RESP中長字符串數組的命令到Redis服務端。Redis服務端根據命令實現回復其中一種RESP類型。在RESP中,一種數據類型基於第一個字節:
對於短字符串,回復的第一個字節是"+"對於錯誤,回復的第一個字節是"-"對於整數,回復的第一個字節是":"對於長字符串,回復的第一個字節是"$"對於數組,回復的第一個字節是"*" 另外RESP能用指定的長字符串或數組的特殊變量來表示空值。
前面說到的協議,我有強調了是client,就是說server回復client請求時用到的協議;client請求server時,只需要在命令後面加上"\r\n"。
下面是5種類型的返回實例:
假設在redis server中存在以下鍵值對: name1 cat age1 10 短字符串 "set name2 fish\r\n" "+OK\r\n" 錯誤 "seet name3 dog" "-ERR unknown command 'seet'\r\n" 整數 "incr age1" ":11" 長字符串 ① "get name1\r\n" "$3\r\ncat\r\n" ② "get name3\r\n" "$-1\r\n" 數組 ① "mget name1 age1\r\n" "*2\r\n$3\r\ncat\r\n$2\r\n11\r\n" ② "mget name2 age2\r\n" "*2\r\n$4\r\nfish\r\n$-1\r\n" ③ 其它情況會返回"*-1\r\n"和"*0\r\n",具體參考redis官方文檔;