redis的ping pong
登录redis cli客户端后, 输入ping, 服务器会返回pong, 来表示连接状况是完好的, 也表示了服务器大体上是正常运转的.
其中的第一行是我用docker 启动的客户端, 大家如果不是docker的话, 自己正常启动redis -cli就行..
ping之后就会收到pong
使用Java socket 来实现 Redis 的ping pong
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi流 OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // 向redis服务器写 os.write("PING\r\n".getBytes()); //从redis服务器读,到bytes中 byte[] bytes = new byte[1024]; int len = is.read(bytes); // to string 输出一下 System.out.println(new String(bytes,0,len)); }
返回的结果如下:
为什么会有一个 '+'符号 呢? redis -cli里是没有这个加号的呀?
这个和通信协议有关, 一会儿再介绍具体的含义. 不过redis -cli只是把这个'+'符号吞掉处理了, 没显示出来罢了。
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi流 OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // 向redis服务器写 os.write("PING\r\n".getBytes()); //从redis服务器读,到bytes中 byte[] bytes = new byte[1024]; if(is.read()=='+'){ // to string 输出一下 int len = is.read(bytes); System.out.println(new String(bytes,0,len)); } // else if $ // else if * // else }
这样就跟redis -cli里的一样啦.就只是pong了
实现SET 和 GET
set:
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi流 OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // 向redis服务器写 os.write("set hello world123\r\n".getBytes()); //从redis服务器读,到bytes中 byte[] bytes = new byte[1024]; int len = is.read(bytes); // to string 输出一下 System.out.println(new String(bytes,0,len)); }
get:
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.310", 6379); // oi流 OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // 向redis服务器写 os.write("get hello\r\n".getBytes()); //从redis服务器读,到bytes中 byte[] bytes = new byte[1024]; int len = is.read(bytes); // to string 输出一下 System.out.println(new String(bytes,0,len)); }
解释上面例子中的+和$符号
加号'+' 是来表示状态回复的, 在redis服务端向客户端返回状态信息时, 就会先发送一个`+`符号来开头.
接下来是相应的状态信息, 例如'OK'什么的.
最后, 要以'\r\n' 来结尾... 咱们看一下代码就明白了
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi流 OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); // 向redis服务器写 os.write("set hello world123\r\n".getBytes()); //从redis服务器读,到bytes中 byte[] bytes = new byte[1024]; if (is.read() == '+') { System.out.println("这是一个状态回复哦! 怎么知道的呢? `+` 号就表示 '状态回复' 了"); int len = is.read(bytes); System.out.println("回复的状态是: " + new String(bytes, 0, len)); } // 大家想不想看看bytes里面到底有几个字符吗? System.out.println(Arrays.toString(bytes)); // 输出的是 [79, 75, 13, 10, 0, 0, 0, 0, 0,....] // 其中 79 75 是 `OK` // 其中 13 10 是 `\r\n` // 后面的一串0 是 表示没有后续内容, 已经读完. }
$ 表示批量读取, 一般格式是: $, 数字来表示正文的内容的字节数
抓包后是这样的, 客户端向服务端发送了"get hello", 服务端向客户端发送了蓝色的这两行.
public static void main(String[] args) throws Exception { // socket Socket socket = new Socket("140.143.135.210", 6379); // oi流 OutputStream os = socket.getOutputStream(); // 为了解析'\r\n'方便, 我就用改为字符流了 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 向redis服务器写 os.write("get hello\r\n".getBytes()); // 缓冲数组 char[] chars = new char[1024]; //从redis服务器读,到bytes中 if (br.read() == '$') { System.out.println("这是一个批量回复哦! 怎么知道的呢? `$` 号就表示 '批量回复' 了"); System.out.println("$ 后面会跟一个数字, 来表示正文内容的大小"); // readLine直接能判断'\r' '\n' int len = Integer.parseInt(br.readLine()); System.out.println("$后面跟着的数字是: " + len + ", 表示正文是" + len + "个字节, 接下来只要读取" + len + "个字节就好了"); // 接下来只读取len个字符就ok了 (其实单位应该是字节, 但是我中途为了readLine省事, 改用了字符流, 个数是不变的) br.read(chars, 0, len); System.out.println("get到的结果是: " + new String(chars, 0, len) + ", 数一数真的是" + len + "个字符"); } }
Redis通信协议就只是这样?
no!!!刚才客户端向服务端发送的 "get hello" , 这种只是"内联命令", 而不是Redis真正的通信协议.
问: 什么意思呢? 答: 就是说你可以像之前那样给服务端发, 服务器端接受到后, 会遍历一遍你发送的内容, 最后根据空格来分析你所发的内容的含义.
问: 这样有什么不好的吗? 答: 如果这样的话, 你就把解析的工作交给了服务器来做, 会加大服务器的工作量.
问: 那怎么样才是符合规范的呢? 符合协议的话真的会提高服务器的效率? 答: 首先看一下符合协议的客户端和服务端之间的交互把.如下例子:
例: set java python ,抓到包之后是这样的:
红色是客户端发送的内容, 蓝色是服务器端返回的内容.
咱们一起解析一下:
*3表示 , 客户端即将发送3段内容
哪三段呢? 第一段: '$3 SET' 第二段: '$4 java' 第三段: '$6 python'
更严格地说: 第一段: '$3\r\nSET\r\n' 第二段:'$4\r\njava\r\n' 第三段:'$6\r\npython\r\n'
$符号的意思在上一小节就已经提到过了, 表示下文的内容的长度, 方便服务器进行读取.
例如: $6就已经把python的长度给汇报出来了, 服务器只需要截取区间[index, index+6]就好了, 不需要去找空格在什么地方(找空格的时间复杂度是O(n), 而$6这种写法是O(1) )
Jedis
其实Jedis做的工作大体就是把SET key value 这样的格式转化为下面这种格式, 然后发到Redis服务端:
*3\r\n $3\r\n SET\r\n $3\r\n key\r\n $5\r\n value\r\n
更多redis知识请关注redis入门教程栏目。
The above is the detailed content of redis communication protocol (protocol). For more information, please follow other related articles on the PHP Chinese website!

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor