In the world , Martial arts in the world , invulnerable , Fast break not only , This sentence is tailor-made for me .
I am a Redis service , I’m most proud of my speed , my QPS Can achieve 10 Wan grade .
There are countless little brothers in my hands , They come to me from time to time to store or take some data , I call them clients , They are also called… In English Redis-client.
Sometimes a little brother comes very often , Sometimes a bunch of kids come at the same time , however , No matter how many kids I have, I can manage them in good order .
one day , The boys asked me .

Think that year , In order not to let the younger brothers drag down my proud speed , When designing communication protocols with them , I racked my brains , The following three principles have been formulated :
-
Implement a simple
-
For computers , The analysis speed is fast
-
For humans , High readability
Why is it so designed ? Let’s take a look at the process of issuing an instruction , First of all, the client needs to encapsulate the instruction operation , Using the network for transmission , Finally, the server side of the corresponding analysis 、 perform .
If this process is designed as a very complex protocol , So encapsulation 、 analysis 、 The transmission process will be very time-consuming , It will definitely slow me down . what , You ask me why I have to follow the last rule ? It’s a gift for programmers , I’m so kind .
I call this agreement created RESP (REdis Serialization Protocol
) agreement , It works in TCP The upper level of the agreement , As a standard form of communication between me and clients .
Speaking of this , I can’t wait to show you my masterpiece , But I’m also a big brother , You have to put on airs , I can’t take the initiative to show you .
So I suggest that you directly use the client to issue a command to the server , Then take out the message corresponding to this command to have a visual look . That being the case , But I’ve been sealed up , Under normal circumstances, you can’t see my internal communication messages , therefore , You can camouflage Become a Redis The service side , To intercept messages from my younger brothers .
It’s also very easy to implement , My relationship with my younger brother is based on Socket To communicate , So start one locally ServerSocket
, Used to monitor Redis Service 6379 port :
public static void server() throws IOException {
ServerSocket serverSocket = new ServerSocket(6379);
Socket socket = serverSocket.accept();
byte[] bytes = new byte[1024];
InputStream input = socket.getInputStream();
while(input.read(bytes)!=0){
System.out.println(new String(bytes));
}
}
Then start redis-cli
client , Send a command :
set key1 value1
At this time , The disguised server will receive the message , Printed on the console :
*3
$3
set
$4
key1
$6
value1
See here , Vaguely see just entered a few keywords , But there are other characters , How to explain , It’s time for me to reveal the format of the protocol message .
I said to the boys , You have to follow the rules when you talk to big brother , Let’s do that. , You should follow the following rules when you request :
*< The number of arguments > CRLF
$< Parameters 1 Byte length of > CRLF
< Parameters 1 The data of > CRLF
$< Parameters 2 Byte length of > CRLF
< Parameters 2 The data of > CRLF
...
$< Parameters N Byte length of > CRLF
< Parameters N The data of > CRLF
First of all, explain the… At the end of each line CRLF
, Converting to a programming language is \r\n
, That is, carriage return and line feed . See here , You can understand why the commands printed on the console are arranged vertically .
In the parsing of the command ,set
、key1
、value1
Would be considered to be 3 Parameters , So the number of parameters is 3, Corresponding to the first line *3
.
The first parameter set
, The length is 3 Corresponding $3
; The second parameter key1
, The length is 4 Corresponding $4
; The third parameter value1
, The length is 6 Corresponding $6
. The next line of each parameter length corresponds to the real parameter data .
See this , Is it easy to understand how an instruction is converted into a protocol message ?

When my little brother sent me a request , As a big brother , I’m going to respond to my brother’s request Command reply 了 , And I have to sort it out according to the content of the reply , Otherwise, I’ll be confused with my instructions .
Simple string
Simple string reply has only one line reply , The content of the reply is +
As the beginning , Line breaks are not allowed , And \r\n
end . There are many instructions that only reply to one after successful execution OK
, This is the format used , Can effectively transmit 、 The cost of parsing is minimized .

Error response
stay RESP Agreement , Error reply can be treated as a variant of simple string reply , The format between them is also very similar , The only difference is that the first character is -
As the beginning , The content of the error reply is usually the error type and the string describing the error .
Error replies appear in some unusual situations , For example, when the wrong command is sent 、 When the number of operands is not right , Will make an error reply . After the client receives an error reply , Will distinguish it from simple string replies , Treat as abnormal .

Integer reply
Integer reply is also widely used , It uses :
As the beginning , With \r\n
end , Used to return an integer . For example, when performing incr
Then returns the value after self increment , perform llen
Returns the length of the array , Or use exists
Command returned 0 or 1 As a judgment, a key
The basis for the existence of , These all use integer replies .

Batch reply
Batch reply , Is a reply to a multiline string . It uses $
As the beginning , Followed by the length of bytes sent , And then there was \r\n
, And then send the actual data , With a final \r\n
end . If the data you want to reply to doesn’t exist , So the length of the reply is -1.

Multiple batch replies
When the server wants to return multiple values , For example, when you return a collection of elements , Will use multiple batch replies . It uses *
As the beginning , The following is the number of returned elements , Then follow a number of batch replies mentioned above .

Come here , Basically, the communication protocol between me and my younger brother is over . Just now you tried to disguise as a server , This will try to write a client directly to interact with me .
private static void client() throws IOException {
String CRLF="\r\n";
Socket socket=new Socket("localhost", 6379);
try (OutputStream out = socket.getOutputStream()) {
StringBuffer sb=new StringBuffer();
sb.append("*3").append(CRLF)
.append("$3").append(CRLF).append("set").append(CRLF)
.append("$4").append(CRLF).append("key1").append(CRLF)
.append("$6").append(CRLF).append("value1").append(CRLF);
out.write(sb.toString().getBytes());
out.flush();
try (InputStream inputStream = socket.getInputStream()) {
byte[] buff = new byte[1024];
int len = inputStream.read(buff);
if (len > 0) {
String ret = new String(buff, 0, len);
System.out.println("Recv:" + ret);
}
}
}
}
Run the above code , Console output :
Recv:+OK
It mimics the client sending out set
The process of command , And received a response . And so on , You can also encapsulate other commands yourself , To achieve one’s own Redis client , As a little brother , To communicate with me .
But remember , Call me big brother .
Official account back office reply
” interview “— Get interview information of large factory
” Guide map “— led take 24 Zhang Java Back end learning note map
” framework “— led take 29 Ben java Architect ebook
” actual combat “— led take springboot Actual project
” video “— led Take the latest java Architect video
<!– –>
Official account
Interesting 、 thorough 、 direct
Talk to you about technology
Feel useful , Four in one ~