RESP协议

 

RESP 是 Redis 序列化协议的简写。它是⼀种直观的⽂本协议,优势在于实现异常简单,解析性能极好。
Redis 协议将传输的结构数据分为 5 种最⼩单元类型,单元结束时统⼀加上回⻋换⾏符号\r\n。
间隔符号,在Linux下是\r\n,在Windows下是\n
1. 单⾏字符串 以 + 符号开头。
2. 多⾏字符串 以 $ 符号开头,后跟字符串⻓度。
3. 整数值 以 : 符号开头,后跟整数的字符串形式。
4. 错误消息 以 - 符号开头。
5. 数组 以 * 号开头,后跟数组的⻓度。
单⾏字符串 hello world
+hello world\r\n
多⾏字符串 hello world
$11\r\nhello world\r\n
整数 1024
:1024\r\n
错误 参数类型错误
-WRONGTYPE Operation against a key holding the wrong kind of value\r\n
数组 [1,2,3]
*3\r\n:1\r\n:2\r\n:3\r\n
NULL ⽤多⾏字符串表示,不过⻓度要写成-1。
$-1\r\n
空串 ⽤多⾏字符串表示,⻓度填 0。
$0\r\n\r\n
注意这⾥有两个\r\n。为什么是两个?因为两个\r\n之间,隔的是空 串。

客户端 -> 服务器

客户端向服务器发送的指令只有⼀种格式,多⾏字符串数组。⽐如⼀ 个简单的 set 指令set author codehole会被序列化成下⾯的字 符串。

服务器 -> 客户端

服务器向客户端回复的响应要⽀持多种数据结构,所以消息响应在结构上要复杂不少。不过再复杂的响应消息也是以上 5 中基本类型的组合。
单⾏字符串响应
127.0.0.1:6379> set author codehole
OK
这⾥的 OK 就是单⾏响应,没有使⽤引号括起来。
+OK
错误响应
127.0.0.1:6379> incr author
(error) ERR value is not an integer or out ofrange
试图对⼀个字符串进⾏⾃增,服务器抛出⼀个通⽤的错误。
-ERR value is not an integer or out of range
整数响应
127.0.0.1:6379> incr books
(integer) 1
这⾥的1就是整数响应
:1
多⾏字符串响应
127.0.0.1:6379> get author
"codehole"
这⾥使⽤双引号括起来的字符串就是多⾏字符串响应
posted @ 2020-07-30 20:59  brady-wang  阅读(627)  评论(0编辑  收藏  举报