目录
1. RESP协议
2. 自定义Socket连接Redis
1. RESP协议
2. 自定义Socket连接Redis
public class MyRedisClient {static Socket s;static PrintWriter writer;static BufferedReader reader;static Object obj;public static void main(String[] args) {try {// 1.建立连接String host = "xx";int port = 6379;s = new Socket(host, port);// 2.获取输出流、输入流writer = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8));reader = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));// 3.发出请求// 3.2.set name helloworldsendRequest("set", "name", "helloworld");// 4.解析响应obj = handleResponse();System.out.println("obj = " + obj);// 3.2.set name 虎哥sendRequest("get", "name");// 4.解析响应obj = handleResponse();System.out.println("obj = " + obj);} catch (IOException e) {e.printStackTrace();} finally {// 5.释放连接try {if (reader != null) reader.close();if (writer != null) writer.close();if (s != null) s.close();} catch (IOException e) {e.printStackTrace();}}}private static Object handleResponse() throws IOException {// 读取首字节int prefix = reader.read();// 判断数据类型标示switch (prefix) {case '+': // 单行字符串,直接读一行return reader.readLine();case '-': // 异常,也读一行throw new RuntimeException(reader.readLine());case ':': // 数字return Long.parseLong(reader.readLine());case '$': // 多行字符串// 先读长度int len = Integer.parseInt(reader.readLine());if (len == -1) {return null;}if (len == 0) {return "";}// 再读数据,读len个字节。我们假设没有特殊字符,所以读一行(简化)return reader.readLine();case '*':return readBulkString();default:throw new RuntimeException("错误的数据格式!");}}private static Object readBulkString() throws IOException {// 获取数组大小int len = Integer.parseInt(reader.readLine());if (len <= 0) {return null;}// 定义集合,接收多个元素List<Object> list = new ArrayList<>(len);// 遍历,依次读取每个元素for (int i = 0; i < len; i++) {list.add(handleResponse());}return list;}// set name 虎哥private static void sendRequest(String ... args) {writer.println("*" + args.length);for (String arg : args) {writer.println("$" + arg.getBytes(StandardCharsets.UTF_8).length);writer.println(arg);}writer.flush();}
}