I used to only use the redis-cli client, or use jedis in the java program as a medium to communicate with the redis server. In the past two days, I just relieved a little of this content during the internship. I flipped over the redis-related content during the May Day holiday. material.
The purpose of this blog is to organize notes for myself, and secondly, to share it with students in school: It is aimed at students who have used redis, but only stay in the basic set get command and do not understand the principle.
Introducing the ping pong of redis
First of all, let me introduce ping pong.. (Some students don't understand.. I will add the introduction of ping pong)
After logging in to the redis cli client, enter ping, the server will return pong, indicating that the connection status is intact, and that the server is generally operating normally.
The first line is the client I started with docker. If you are not docker, you can start redis-cli normally..
After ping, you will receive pong
Use Java socket to implement Redis ping pong
When copying the code, everyone should be more conscientious...don't try it with my ip...(It doesn't matter if you have to take my test...because I have secretly changed one digit)
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi style OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // write to redis server os.write("PING\r\n".getBytes()); //Read from redis server to bytes byte[] bytes = new byte[1024]; int len = is.read(bytes); // to string output System.out.println(new String(bytes,0,len)); }
The results returned are as follows:
Q: Why is there a '+' symbol? There is no such plus sign in redis-cli? A: This is related to the communication protocol, and the specific meaning will be introduced later. However, redis-cli only uses this '+' symbol It's swallowed and processed, and it's not displayed. If you don't understand it... Look at the code below...
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi style OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // write to redis server os.write("PING\r\n".getBytes()); //Read from redis server to bytes byte[] bytes = new byte[1024]; if(is.read()=='+'){ // to string output int len = is.read(bytes); System.out.println(new String(bytes,0,len)); } // else if $ // else if * // else }
This is the same as in redis-cli. It's just pong
ps: I'm not kidding everyone.... jedis is also written like this at the protocol layer, and the symbols $ * + are judged one by one to determine the meaning of the transmission content...
Next, let's implement SET and GET.