Home Database Redis redis communication protocol (protocol)

redis communication protocol (protocol)

May 22, 2020 am 09:06 AM
redis

redis communication protocol (protocol)

redis的ping pong

登录redis cli客户端后, 输入ping, 服务器会返回pong, 来表示连接状况是完好的, 也表示了服务器大体上是正常运转的.

redis communication protocol (protocol)

其中的第一行是我用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));
    }
Copy after login

返回的结果如下:

redis communication protocol (protocol)

为什么会有一个 '+'符号 呢? 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
    }
Copy after login

这样就跟redis -cli里的一样啦.就只是pong了

redis communication protocol (protocol)

实现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));
    }
Copy after login

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));
    }
Copy after login

redis communication protocol (protocol)

解释上面例子中的+和$符号

加号'+' 是来表示状态回复的, 在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 是 表示没有后续内容, 已经读完.
    }
Copy after login

$ 表示批量读取, 一般格式是: $<数字>, 数字来表示正文的内容的字节数

redis communication protocol (protocol)

抓包后是这样的, 客户端向服务端发送了"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();
        // 为了解析&#39;\r\n&#39;方便, 我就用改为字符流了
        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() == &#39;$&#39;) {
            System.out.println("这是一个批量回复哦! 怎么知道的呢? `$` 号就表示 &#39;批量回复&#39; 了");
            System.out.println("$ 后面会跟一个数字, 来表示正文内容的大小");
            // readLine直接能判断&#39;\r&#39; &#39;\n&#39;
            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 + "个字符");
        }
    }
Copy after login

Redis通信协议就只是这样?

no!!!刚才客户端向服务端发送的 "get hello" , 这种只是"内联命令", 而不是Redis真正的通信协议.

问: 什么意思呢? 答: 就是说你可以像之前那样给服务端发, 服务器端接受到后, 会遍历一遍你发送的内容, 最后根据空格来分析你所发的内容的含义.

问: 这样有什么不好的吗? 答: 如果这样的话, 你就把解析的工作交给了服务器来做, 会加大服务器的工作量.

问: 那怎么样才是符合规范的呢? 符合协议的话真的会提高服务器的效率? 答: 首先看一下符合协议的客户端和服务端之间的交互把.如下例子:

例: set java python ,抓到包之后是这样的:

redis communication protocol (protocol)

红色是客户端发送的内容, 蓝色是服务器端返回的内容.

咱们一起解析一下:

*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
Copy after login

更多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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to make message middleware for redis How to make message middleware for redis Apr 10, 2025 pm 07:51 PM

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.

See all articles