当前位置:网站首页>Redis communication protocol -- resp protocol
Redis communication protocol -- resp protocol
2022-07-28 03:22:00 【March never dies】
Redis Communication protocol –RESP agreement
Redis It's a CS Architecture software , Communication is generally divided into two steps ( barring pipeline and PubSub) :
1) client (client) To the server ( server) Send a command
2) The server parses and executes commands , Return the response result to the client
Therefore, the format of the command sent by the client 、 The format of the server response result must have a specification , This specification is the communication protocol .
And in the Redis It is used in RESP ( Redis Serialization Protocol) agreement :
- Redis 1.2 Version introduced RESP agreement
- Redis 2.0 In the version, it becomes the same as Redis The standard of server communication , be called RESP2
- Redis 6.0 In the version , from RESP2 Upgrade to RESP3 agreement , Add more data types and support 6.0 New features – Client cache
But at the moment, , The default is still RESP2 agreement , It is also the protocol version we need to learn ( hereinafter referred to as RESP).
REPS agreement : When the client sends a command to the server, or the server returns the result to the client , Comply with certain specifications
RESP agreement - data type
stay RESP in , Distinguish different data types by the characters of the first byte , Common data types include 5 Kind of :
Single line string : The first byte is ’+', Followed by a single line string , With CRLF (“\r\n”) ending . Such as return "OK":—>“+OK\r\n”
error (Errors)∶ The first byte is ’-', Same format as single line string , It's just that the string is an exception message , for example :“-Error message\r\n”
The number : The first byte is ’:', Followed by a string in numeric format , With CRLF ending . for example : “:10\r\n”
Multiline string : The first byte is ‘$’, A string representing binary security , The biggest support 512MB:
- If the size is 0, Represents an empty string :“$0\r\n\r\n”
- If the size is -1, It means it doesn't exist :“$-1\r\n”
- If the size is 5, Is represented as :“$5\r\nhello\r\n”
Array : The first byte is ‘*’, Followed by the number of array elements , Keep up with the elements , The element data type is unlimited :
*3\r\n --> Number of array elements , The following three are array elements
:10\r\n
$5\r\nhello\r\n
*2\r\n$3\r\nage\r\n"10\r\n
Be careful :
Single line string : Cannot have /r/n Special characters for , Read /r/n ends , Generally, a single line string is used in the result return
error : If there is an error on the server , Return the exception Prompt string
Multiline string : Record string length , Then read the specified length to represent the end
Array : The element type can be any of the above
redis The request is usually an array , Such as set name sanyue It will be converted into an array and sent to the server for parsing
simulation redis The client sends commands and parses data
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class Main {
static Socket s;
static PrintWriter writer;
static BufferedReader reader;
public static void main(String[] args) {
try {
// 1. Establishing a connection
String host = "192.168.150.101";
int port = 6379;
s = new Socket(host, port);
// 2. Get the output stream 、 Input stream
writer = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8));//tcp Send a request , That is to say socket Sending data in , get data , Also from the socket In order to get
reader = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));// Manage application byte stream , But here for the convenience of using character stream , According to the line read
// 3. Request
// 3.1. Get authorization auth 123321
sendRequest("auth", "123456");//redis Set the password and authorize
Object obj = handleResponse();
System.out.println("obj = " + obj);
// 3.2.set name March
sendRequest("set", "name", " March ");
// 4. Parse response
obj = handleResponse();
System.out.println("obj = " + obj);
// 3.2.set name March
sendRequest("get", "name");
// 4. Parse response
obj = handleResponse();
System.out.println("obj = " + obj);
// 3.2.set name Tiger brother
sendRequest("mget", "name", "num", "msg");
// 4. Parse response
obj = handleResponse();
System.out.println("obj = " + obj);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 5. Release the connection
try {
if (reader != null) reader.close();
if (writer != null) writer.close();
if (s != null) s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Parse command set name sanyue
/**set name sanyue *3/r/n $3/r/nset/r/n $4/r/nname/r/n $/6/r/nsanyue/r/n */
private static void sendRequest(String ... args) {
writer.println("*" + args.length);// Character stream println Line breaks will be printed at the end
for (String arg : args) {
writer.println("$" + arg.getBytes(StandardCharsets.UTF_8).length);
writer.println(arg);
}
writer.flush();
}
// Parse command
private static Object handleResponse() throws IOException {
// Read the first byte
int prefix = reader.read();
// Judge the data type mark
switch (prefix) {
case '+': // Single line string , Just read one line
return reader.readLine();
case '-': // abnormal , Read a line, too
throw new RuntimeException(reader.readLine());
case ':': // Numbers
return Long.parseLong(reader.readLine());
case '$': // Multiline string
// Read the length first
int len = Integer.parseInt(reader.readLine());
if (len == -1) {
return null;
}
if (len == 0) {
return "";
}
// Read the data again , read len Bytes . We assume that there are no special characters , So read a line ( simplify )
return reader.readLine();
case '*':
return readBulkString();
default:
throw new RuntimeException(" Bad data format !");
}
}
private static Object readBulkString() throws IOException {
// Get array size
int len = Integer.parseInt(reader.readLine());
if (len <= 0) {
return null;
}
// Define a collection , Receive multiple elements
List<Object> list = new ArrayList<>(len);
// Traverse , Read each element in turn
for (int i = 0; i < len; i++) {
list.add(handleResponse());
}
return list;
}
}
边栏推荐
- max_pool2d(): argument ‘input‘ (position 1) must be Tensor, not NoneType
- 数据湖(十七):Flink与Iceberg整合DataStream API操作
- Exness: Japanese prices rose and incomes fell, with the pound / yen breaking 165
- Comprehensive comparative study of image denoising
- 【AcWing 327. 玉米田】状压dp
- JVM memory layout detailed, illustrated, well written!
- 关于权重衰退和丢弃法
- 力扣(LeetCode)208. 实现 Trie (前缀树)(2022.07.27)
- On weight decay and discarding method
- C # set TextBox control not editable
猜你喜欢

QFileDevice、QFile、QSaveFile、QTemporaryFile

Redis内存回收

【2022 牛客第二场J题 Link with Arithmetic Progression】三分套三分/三分极值/线性方程拟合最小二乘法

Shell:一键部署pxe

Decision tree and random forest learning notes (1)

Exness: Japanese prices rose and incomes fell, with the pound / yen breaking 165

会议OA项目之我的审批&&签字功能

Games101 review: ray tracing

Tungsten Fabric SDN — BGP as a Service

What if the word selection box of win11 input method is missing?
随机推荐
20条心灵鸡汤唯美句子,句句温情暖心!
20 soul chicken soup beautiful sentences, sentence by sentence warm heart!
[acwing 327. corn field] shaped pressure DP
ssm整合(整合配置)
[2022 Niuke Game 2 J question link with arithmetic progress] three part set three part / three part extreme value / linear equation fitting least square method
IronOCR for .NET 2022.8
Talk about the speech synthesis function of Baidu University of science and technology news Feiyun Zhisheng
More than 50 interviews have been summarized, and notes and detailed explanations have been taken from April to June (including core test sites and 6 large factories)
Uniapp——拨打电话、发送短信
Brush questions every day to consolidate knowledge
方案分享 | 高手云集 共同探索重口音AI语音识别
数字孪生技术驱动智能工厂减负赋能提升运维效益
Thread Foundation
Design of the multi live architecture in different places of the king glory mall
Leaf recognition, color feature extraction, defect detection, etc
【AcWing 327. 玉米田】状压dp
嵌入式数据库--SQLite
Intelligent industrial design software company Tianfu C round financing of hundreds of millions of yuan
exness:日本物价上涨收入下降,英镑/日元突破 165
PCB丝印如何摆?请查收这份手册!