咱們用過不少redis的客戶端,有沒有相過本身擼一個redis客戶端? 其實很簡單,基於socket,監聽6379端口,解析數據就能夠了。redis
解析數據的過程主要依賴於redis的協議了。 咱們寫個簡單例子看下redis的協議:數組
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"); } }
監聽socket:app
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)); }
看下數據:socket
*3 $3 SET $3 eat $13 I want to eat
參照官方協議文檔https://redis.io/topics/protocol, 解析下數據。測試
(1)簡單字符串 Simple Strings, 以 "+"加號 開頭 (2)錯誤 Errors, 以"-"減號 開頭 (3)整數型 Integer, 以 ":" 冒號開頭 (4)大字符串類型 Bulk Strings, 以 "$"美圓符號開頭,長度限制512M (5)組類型 Arrays,以 "*"星號開頭 而且,協議的每部分都是以 "\r\n" (CRLF) 結尾的。ui
因此上面的數據的含義是:this
*3 數組包含3個元素,分別是SET、eat、I want to eat $3 是一個字符串,且字符串長度爲3 SET 字符串的內容 $3 是一個字符串,且字符串長度爲3 eat 字符串的內容 $13 是一個字符串,且字符串長度爲13 I want to eat 字符串的內容
執行get 'eat'的數據以下:code
*2 $3 GET $3 eat
掌握了redis協議,socket以後,咱們就能夠嘗試擼一個客戶端了。server
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協議:
public String set(final String key, String value) { StringBuilder sb = new StringBuilder(); //雖然輸出的時候,會被轉義,然而咱們傳送的時候仍是要帶上\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);
執行結果:
+OK