共計 2045 個字符,預計需要花費 6 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
如何使用 Redis 協(xié)議?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
redis 協(xié)議
解析數(shù)據(jù)的過程主要依賴于 redis 的協(xié)議了。我們寫個簡單例子看下 redis 的協(xié)議:
public class RedisTest { public static void main(String[] args) { Jedis jedis = new Jedis( 127.0.0.1 , 6379); jedis.set(eat , I want to eat }}
監(jiān)聽 socket:
public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(6379); Socket socket = server.accept(); byte[] chars = new byte[64]; socket.getInputStream().read(chars); System.out.println(new String(chars)); }
看下數(shù)據(jù):
*3$3SET$3eat$13I want to eat
參照官方協(xié)議文檔 https://redis.io/topics/protocol,解析下數(shù)據(jù)。
(1)簡單字符串 Simple Strings, 以 + 加號 開頭(2)錯誤 Errors, 以 – 減號 開頭(3)整數(shù)型 Integer,以 : 冒號開頭(4)大字符串類型 Bulk Strings, 以 $ 美元符號開頭,長度限制 512M(5)組類型 Arrays,以 * 星號開頭并且,協(xié)議的每部分都是以 \r\n (CRLF) 結尾的。
所以上面的數(shù)據(jù)的含義是:
*3 數(shù)組包含 3 個元素,分別是 SET、eat、I want to eat$3 是一個字符串,且字符串長度為 3SET 字符串的內(nèi)容 $3 是一個字符串,且字符串長度為 3eat 字符串的內(nèi)容 $13 是一個字符串,且字符串長度為 13I want to eat 字符串的內(nèi)容
執(zhí)行 get eat 的數(shù)據(jù)如下:
*2$3GET$3eat
擼一個客戶端
掌握了 redis 協(xié)議,socket 之后,我們就可以嘗試擼一個客戶端了。
socket:
public RedisClient(String host, int port){ try { this.socket = new Socket(host,port); this.outputStream = this.socket.getOutputStream(); this.inputStream = this.socket.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
set 協(xié)議:
public String set(final String key, String value) { StringBuilder sb = new StringBuilder(); // 雖然輸出的時候,會被轉(zhuǎn)義,然而我們傳送的時候還是要帶上 \r\n sb.append(*3).append(\r\n sb.append( $3).append(\r\n sb.append( SET).append(\r\n sb.append( $).append(key.length()).append(\r\n sb.append(key).append(\r\n sb.append( $).append(value.length()).append(\r\n sb.append(value).append(\r\n byte[] bytes= new byte[1024]; try { outputStream.write(sb.toString().getBytes()); inputStream.read(bytes); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new String(bytes); }
測試:
RedisClient redisClient = new RedisClient(127.0.0.1 , 6379); String result = redisClient.set(eat , please eat System.out.println(result);
執(zhí)行結果:
+OK
看完上述內(nèi)容,你們掌握如何使用 Redis 協(xié)議的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注丸趣 TV 行業(yè)資訊頻道,感謝各位的閱讀!
向 AI 問一下細節(jié)