redis-protocol
08 March 2018
原文: 通信协议(protocol)

RESP

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 "*"

RESP Simple Strings

"+OK\r\n"

RESP Errors

"-Error message\r\n"

"-ERR unknown command 'foobar'\r\n"
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"

RESP Integers

":0\r\n"
":1000\r\n"

RESP Bulk Strings

"$6\r\nfoobar\r\n"   foobar
"$0\r\n\r\n"         (empty string)
"$-1\r\n"            (null)

void addReplyBulk(client *c, robj *obj) {
    addReplyBulkLen(c, obj);
    addReply(c, obj);
    addReply(c, shared.crlf);
}

void addReplyBulkLen(client *c, robj *obj) {
    size_t len;

    if (sdsEncodedObject(obj)) {
        len = sdslen(obj->ptr);
    } else {
        long n = (long) obj->ptr;

        /* Compute how many bytes will take this integer as a radix 10 string */
        len = 1;
        if (n < 0) {
            len++;
            n = -n;
        }
        while ((n = n / 10) != 0) {
            len++;
        }
    }

    if (len < OBJ_SHARED_BULKHDR_LEN) {
        addReply(c, shared.bulkhdr[len]);
    } else {
        addReplyLongLongWithPrefix(c, len, '$');
    }
}

RESP Arrays

"*0\r\n"                                              (empty array)
"*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n"                    (2 arrays, ["foo", "bar"])
"*3\r\n:1\r\n:2\r\n:3\r\n"                            (3 arrays, [1, 2, 3])
*5\r\n:1\r\n:2\r\n:3\r\n:4\r\n$6\r\nfoobar\r\n        (5 arrays, [1, 2, 3, 4, 6, "foobar"])
"*-1\r\n"                                             (null arrays)
*2\r\n*3\r\n:1\r\n:2\r\n:3\r\n*2\r\n+Foo\r\n-Bar\r\n  (arrays of arrays, [[1, 2, 3], ["Foo", "Bar"]])

void addReplyMultiBulkLen(client *c, long length) {
    if (length < OBJ_SHARED_BULKHDR_LEN) {
        addReply(c, shared.mbulkhdr[length]);
    } else {
        addReplyLongLongWithPrefix(c, length, '*');
    }
}

Sending commands to a Redis Server

C: *2\r\n
C: $4\r\n
C: LLEN\r\n
C: $6\r\n
C: mylist\r\n

S: :48293\r\n

C: PING
S: +PONG