Redis 客户端与服务端之间的通信协议是在 TCP 协议上构建的。Redis 定义了 RESP(Redis Serialization Protocol,Redis 序列化协议)实现客户端与服务端的通信,协议本身很简洁。
请求格式
*<参数数量>CRLF
$<参数1的字节数>CRLF
<参数1>CRLF
...
$<参数N的字节数>CRLF
<参数N>CRLF
例如:SET hello world
*3\r\n
$3\r\n
SET\r\n
$5\r\n
hello\r\n
$5\r\n
world\r\n
上面的示例是格式化显示的结果,实际传输格式为如下:
*3\r\n$3\r\nSET\r\n$5\r\nhello\r\n$5\r\nworld\r\n
返回结果格式
- 状态回复:第一个字节为“+”。
- 错误回复:第一个字节为“-”。
- 整数回复:第一个字节为“:”。
- 字符串回复:第一个字节为“$”。
- 多条字符串回复:第一个字节为“*”。
# nc 127.0.0.1 6379
set hello world
+OK
sethx hello world
-ERR unknown command 'sethx'
incr counter
:1
get hello world
$5
hello
keys hel*
*1
$5
hello