当前位置:网站首页>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;
}
}
边栏推荐
- 20 soul chicken soup beautiful sentences, sentence by sentence warm heart!
- GNU 通用公共许可证 v2.0 GNU GENERAL PUBLIC LICENSE
- Win11黑色桌面背景如何解决?
- 【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发2/100
- Exness: Japanese prices rose and incomes fell, with the pound / yen breaking 165
- C#WinForm开发:如何将图片添加到项目资源文件(Resources)中
- max_ pool2d(): argument ‘input‘ (position 1) must be Tensor, not NoneType
- 随机森林与集成方法学习笔记
- Pytoch correlation gradient echo
- 【ACwing 1064 小国王】状压dp
猜你喜欢

傅里叶级数

max_pool2d(): argument ‘input‘ (position 1) must be Tensor, not NoneType

Stop paging with offset and limit. The performance is too poor!

When QML uses layout layout, a large number of < unknown file >: QML qquicklayoutattached: binding loop detected for property circular binding warnings appear

叶子识别 颜色的特征提取 缺陷检测等

Full of dry goods, hurry in!!! Easy to master functions in C language

数据湖(十七):Flink与Iceberg整合DataStream API操作

"Introduction to engineering electromagnetic field" after class exercises with answers

Win11怎么显示固定应用?

Redis5种数据结构解析
随机推荐
Decision tree and random forest learning notes (1)
如何一键进行重装Win11系统
Web服务器
Redis实现分布式锁
C WinForm development: how to add pictures to project resources
Intelligent industrial design software company Tianfu C round financing of hundreds of millions of yuan
会议OA项目之我的审批&&签字功能
QFileDevice、QFile、QSaveFile、QTemporaryFile
Embedded sharing collection 22
汇总了50多场面试,4-6月面经笔记和详解(含核心考点及6家大厂)
【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发2/100
Redis通信协议--RESP协议
vi命令详解
[acwing 1064 little king] shaped pressure DP
上位机与MES对接的几种方式
Softek Barcode Reader 9.1.5
"Introduction to engineering electromagnetic field" after class exercises with answers
When a dialog box pops up, the following form is not available
stm32F407-------FPU学习
GNU 通用公共许可证 v2.0 GNU GENERAL PUBLIC LICENSE