前言
我們用過很多redis的客戶端,有沒有相過自己擼一個(gè)redis客戶端?其實(shí)很簡(jiǎn)單,基于socket,監(jiān)聽6379端口,解析數(shù)據(jù)就可以了。
redis協(xié)議
解析數(shù)據(jù)的過程主要依賴于redis的協(xié)議了。我們寫個(gè)簡(jiǎn)單例子看下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)簡(jiǎn)單字符串 Simple Strings, 以 "+"加號(hào) 開頭(2)錯(cuò)誤 Errors, 以"-"減號(hào) 開頭(3)整數(shù)型 Integer, 以 ":" 冒號(hào)開頭(4)大字符串類型 Bulk Strings, 以 "$"美元符號(hào)開頭,長(zhǎng)度限制512M(5)組類型 Arrays,以 "*"星號(hào)開頭并且,協(xié)議的每部分都是以 "\r\n" (CRLF) 結(jié)尾的。
所以上面的數(shù)據(jù)的含義是:
*3 數(shù)組包含3個(gè)元素,分別是SET、eat、I want to eat$3 是一個(gè)字符串,且字符串長(zhǎng)度為3SET 字符串的內(nèi)容$3 是一個(gè)字符串,且字符串長(zhǎng)度為3eat 字符串的內(nèi)容$13 是一個(gè)字符串,且字符串長(zhǎng)度為13I want to eat 字符串的內(nèi)容
執(zhí)行g(shù)et 'eat'的數(shù)據(jù)如下:
擼一個(gè)客戶端
掌握了redis協(xié)議,socket之后,我們就可以嘗試擼一個(gè)客戶端了。
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(); //雖然輸出的時(shí)候,會(huì)被轉(zhuǎn)義,然而我們傳送的時(shí)候還是要帶上\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); }
測(cè)試:
RedisClient redisClient = new RedisClient("127.0.0.1", 6379); String result = redisClient.set("eat", "please eat"); System.out.println(result);
執(zhí)行結(jié)果:
更多Redis相關(guān)技術(shù)文章,請(qǐng)?jiān)L問Redis教程欄目進(jìn)行學(xué)習(xí)!