redis通信协议

标准文档:https://redis.io/topics/protocol

优点:简单易实现,高速解析,可读性强

  • Simple to implement.
  • Fast to parse.
  • Human readable

请求-响应模型

客户端一组参数组成的指令,服务端接受后,处理并返回结果。
支持流水线式操作:客户端发送多个指令,统一处理完毕后返回结果
支持订阅/发布模式,当客户端订阅时,服务端会在客户端push后自动返回消息。(不是很懂。。。)

RESP协议描述

支持数据类型:Simple Strings, Errors, Integers, Bulk Strings and Arrays.
请求-响应处理过程:
客户端发送指令,指令用字符串形式的RESP数组(RESP Array of Bulk Strings)表示。
服务端根据指令执行结果,返回处理结果RESP类型。

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 "*"
In RESP different parts of the protocol are always terminated with " " (CRLF).

协议中使用CRLF来区分各个部分。协议形如:

*<参数数量> CR LF
$<参数 1 的字节数量> CR LF
<参数 1 的数据> CR LF
...
$<参数 N 的字节数量> CR LF
<参数 N 的数据> CR LF

RESP Simple Strings

表示返回成功
"+OK "

RESP Errors

表示返回错误
"-Error message "

RESP Integers

For example ":0 ", or ":1000 " are integer replies.
返回int的指令: SETNX, DEL, EXISTS, INCR, INCRBY, DECR, DECRBY, DBSIZE, LASTSAVE, RENAMENX, MOVE, LLEN, SADD, SREM, SISMEMBER, SCARD.

RESP Bulk Strings

"$6 foobar "
最大为512M,结构如下:

  • 以"$"作为开始,紧接着一个数字表示长度,接着是分隔符CRLF
  • 实际的string内容
  • 表示结束的分隔符CRLF

其中"$-1 "表示空。

RESP Arrays

*5

:1

:2

:3

:4

$6

foobar

结构如下:

  • 以"*"作为开始,紧接着一个数字表示参数数量,接着是分隔符CRLF
  • 数组的实际内容(RESP格式),即'符号+内容+分隔符'
  • 支持多类型混搭
  • 支持数组嵌套

Null elements in Arrays

用于表示空元素
$-1

原文地址:https://www.cnblogs.com/omg-two/p/12558282.html