根据老师在课堂上讲的resp协议,手撸一个redis-cli,可以直接与server交互
package test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//测试使用,不做流处理关闭
public class ClientTest {
static Socket socket=null;
public static void main(String[] args) throws IOException {
start("127.0.0.1",6379);
}
private static void start(String s, int port) throws IOException {
//连接server
socket = new Socket(s, port);
//
setS("test","mxd");
getS("test");
}
//resp协议 *3是3个参数 set key value ,$代表输入几个字节,\r\n回车换行
private static void setS(String key, String val) throws IOException {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
StringBuffer s = new StringBuffer();
s.append("*3").append("\r\n");
s.append("$3").append("\r\n");
s.append("set").append("\r\n");
s.append("$").append(key.getBytes().length).append("\r\n");
s.append(key).append("\r\n");
s.append("$").append(val.getBytes().length).append("\r\n");
s.append(val).append("\r\n");
out.write(s.toString().getBytes());
byte[] bytes = new byte[1024];
//把服务器返回的读入输入流中
int len = in.read(bytes);
System.out.println(new String(bytes,0,len));
}
private static void getS (String key) throws IOException{
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
StringBuffer s = new StringBuffer();
s.append("*2").append("\r\n");
s.append("$3").append("\r\n");
s.append("get").append("\r\n");
s.append("$").append(key.getBytes().length).append("\r\n");
s.append(key).append("\r\n");
out.write(s.toString().getBytes());
byte[] bytes = new byte[1024];
//把服务器返回的读入输入流中
int len = in.read(bytes);
System.out.println(new String(bytes,0,len));
}
}