Redis 協議規範

2021-10-11 02:21:05 字數 2837 閱讀 3773

3. 如何快速插入億級的鍵值對

4. 碎碎念

5.參考資料

偶然間跟同事討論起 redis 的 client 和 server 之間傳輸資料的協議是什麼樣子的,以set hello world為例:

我:set hello 5\r\nworld\r\n

同事 z:*3\r\n$3\r\nset\r\n$5\r\nhello\r\n$5\r\nworld\r\n

但是這兩種回答都是對的。因為偷懶的我閱讀的原始碼是 1.3.6 的版本,但是勤奮的同事閱讀的是 3.2 版本的原始碼。你看,就跟考試一樣,有的時候你遇到的可能並非是一項單選題,而更多的時候其實是多選題哦。

既然這樣,那不如順手學習一下 redis 的協議規範 —— resp (redis serialization protocol)。

本著「實事求是」的精深,用 go 寫了乙個簡單的 redis-cli 的 client。**的內容如下(ps 嗯,沒錯,就是 go

package main

import

("fmt"

"net"

)func

main()

conn, err := net.

dialtcp

("tcp"

,nil

, tcpaddr)

if err !=

nil// 注:content3_2 為 3.2 版本的 redis-cli 的資料傳入格式

// content3_2 := "*3\r\n$3\r\nset\r\n$5\r\nhello\r\n$5\r\nworld\r\n"

// 注:content1_3 為 1.3.6 版本的 redis-cli 的資料傳入格式

// content1_3 := "set hello 5\r\nworld\r\n"

// 注:手動拼寫 redis 協議,解決億級別資料快速插入的問題,後面的部分會詳細介紹(ps 此處可以不用關心

contentbatch3_2 :=

"*3\r\n$3\r\nset\r\n$5\r\nhello\r\n$5\r\nworld\r\n*3\r\n$3\r\nset\r\n$5\r\nhelli\r\n$5\r\nworld\r\n*3\r\n$3\r\nset\r\n$5\r\nhellx\r\n$5\r\nworld\r\n"

content := contentbatch3_2

_, err = conn.

write([

]byte

(content)

)if err !=

nil fmt.

printf

("write to server = %s \n"

, content)

reply :=

make([

]byte

,1024)_

, err = conn.

read

(reply)

if err !=

nil fmt.

printf

("read from server = %s \n"

, reply)

conn.

close()

}

由下圖截圖可證,上述的手拼協議插入 1.3.6 版本完全可行

由下圖截圖可證,上述的手拼插入 3.2 版本也是闊以的

要開始測試我用 1.3.6 的 redis 資料格式是否能夠插入到 3.2 版本的 redis 中。

1.3.6 版本寫入的內容為"set hello 5\r\nworld\r\n"

但是在 3.2 版本的 server 中的解析實際上是分為兩部分的:

注:根據上述分析,答案應該是木有的,為什麼呢?因為筆者看**並沒有看到相容的地方 + 測下來就是不相容的。

顯然 ping pong 一來一回的資料插入方式對於億級鍵值對的資料插入必然會很慢。所以其實這裡存在兩種快速插入大量資料的方式:

具體的詳細介紹可以見參考 redis mass insertion 。

作為乙個好奇寶寶,筆者一定是實踐測試了的。

這種方式就是把待插入的資料儲存在乙個檔案中,然後用 --pipe 的方式插入,具體如下圖所示:

這種插入方式說白了就是在基於 redis 協議在一條訊息體內寫入多個 key value 的鍵值對(ps 拼寫的訊息格式"*3\r\n$3\r\nset\r\n$5\r\nhello\r\n$5\r\nworld\r\n*3\r\n$3\r\nset\r\n$5\r\nhelli\r\n$5\r\nworld\r\n*3\r\n$3\r\nset\r\n$5\r\nhellx\r\n$5\r\nworld\r\n",具體如下圖所示:

好啦,橫跨兩個月的學習筆記終於寫完了。記錄下最近看到的驚豔自己的幾句話吧。(ps 真從 11 月開始寫,到 12 月 1 日才剛剛寫完,深感愧疚……

Redis協議規範 RESP

redis 即 remote dictionary server 遠端字典服務 而redis的協議規範是 redis serialization protocol redis序列化協議 該協議是用於與redis伺服器通訊的,用的較多的是redis cli通過pipe與redis伺服器聯絡 協議如下 ...

STOMP協議規範

原文 stomp protocol specification,version 1.2 摘要stomp是乙個簡單的可互操作的協議,被用於通過中間伺服器在客戶端之間進行非同步訊息傳遞。它定義了一種在客戶端與服務端進行訊息傳遞的文字格式.stomp已經被使用了很多年,並且支援很多訊息brokers和客戶...

BitTorrent 協議規範(BT協議集合)七

bt種子檔案使用了一種叫bencoding的編碼方法來儲存資料。bencoding現有四種型別的資料 srings 字串 integers 整數 lists 列表 dictionaries 字典 編碼規則如下 strings 字串 編碼為 字串長度 字串 例如 4 test 表示為字串 test 4...