前置知识Resp
Redis的序列化协议(Redis Serialization Protocol),直观的文本协议,优点:实现简单,解析性能好
传输5种最小的数据类型,单元结束统一使用 \r\n
单行字符串使用+开头 +hello world\r\n
多行使用$开头,后跟字符串长度 $11\r\nhello world\r\n
整数以:开头后跟整数的字符串形式 :1024\r\n
错误消息以-开头 -WRONGTYPE OpenXXX
数组以*开头后跟数组长度 *3\r\n:1\r\n:2\r\n:3\r\n 数组【1,2,3】
注意null使用$-1\r\n表示 空串使用$0\r\n\r\n表示
客服端只会向服务端发送多行字符串数组 服务端向客服端响应是多种格式的组合
因此只需要一个Socket连接然后按协议处理内容就行了
代码
public class MyRedis {
private static final String HOST="8.131.68.141";
private static final int PORT=9003;
private static final String EXIT="exit";
private static byte[] bytes;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
Socket socket = new Socket(HOST, PORT);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
bytes=new byte[1024];
while (true){
String line = scanner.nextLine();
if(exit(line)){
scanner.close();
in.close();
out.close();
socket.close();
System.exit(0);
}else {
handleOut(line,out);
printIn(in);
}
}
}
// 这里 可以进一步完善 根据协议格式化显示
private static void printIn(InputStream in) throws IOException {
int read = in.read(bytes);
System.out.println(new String(bytes,0,read));
}
private static void handleOut(String line, OutputStream out) throws IOException {
String[] split = line.split("\\s+");
StringBuilder builder=new StringBuilder();
builder.append('*').append(split.length).append("\r\n");
for (String item:split){
builder.append('$').append(item.length()).append("\r\n").append(item).append("\r\n");
}
out.write(builder.toString().getBytes());
}
private static boolean exit(String line) {
return EXIT.equals(line);
}
}