search
HomeDatabaseRedisDetailed explanation of Redis RESP protocol implementation examples

Recommended learning: Redis video tutorial

Review RESP protocol

RESP is a Redis communication protocol based on TCP. The protocol is divided by /r/n (line), and the protocol supports 5 types, the specific information is as follows:

##TypePrefixRemarks Simple string Simple string starts with Error data-Error data starts with -Start with Integer:Integer starts with:Complex string$Complex string starts with $Array*Array starts with *

即,我们向redis发送命令:set name pdudo,其实发送的具体信息是

*3
$3
set
$4
name
$5
pdudo

而服务器返回的信息也是类似的,只不过还需要了解+-,这2个前缀分别代表正确消息和错误的消息。

我们准备2个例子,我们来敲一下

例子1

set name pdudo

例子2

lpush pdudo data1
lpush pdudo data2
lrange pdudo 0 -1

快来动动你的小手指,看能不能根据RESP协议规则,将上述例子命令敲出来。现在你体会到了Redis官网介绍RESP协议时所述的 简单易读 可么?

对于RESP来说,一定要搞清楚协议后,最好能够手写协议去执行,再考虑写程序去实现协议!!!

如何拆解RESP协议

终于到了喜闻乐见的环节了,我们要拆解和组装协议了。 那我们至少来解决如下3个问题:

  • 该协议是基于TCP流的,我们如何判断整个命令什么时候结束?
  • 如何拆解命令?

协议什么时候结束

一般而言,我们自己在使用TCP传输数据,都会在数据开头定义2个或者4个字节,用于存储该数据有多少个字节,这样方便检验接收,类似于这种情况。

RESP有意思了,它是以/r/n来分割的。最前面会以前缀来判断其类型,例如我们发送命令,其会用到的前缀有*以及$,那么我们如何来判断,我们要读取多少个/r/n呢?

因为上述*代表数组,即有多少组数据需要处理,图中为n

$表示复杂字符串,即需要获取m个字符数据,不包含/r/n

如何拆解RESP协议

若要拆解命令,则我们得获取命令,如上图所示,报文$m,其实记录的有m长度的数据(不包含\r\n),所以我们可以这样来写伪代码。

根据如上,我们很容易写出伪代码

func toArgs(rd *bufio.Reader) {
	data , _ , _ := rd.ReadLine()
	switch data[0] {
	case '*':
		n := data[1:] // 循环n次
		for i:=0;i<n;i++ {
			toArgs(rd)
		}
	case &#39;$&#39;:
		m := data[1:] // 获取m个数据
		// 获取m长度的数据即可
	}
}

如上我们先获取前缀为*的,继而获取其值n,我们则循环n次,即可获取该报文的数据。而前缀为$的,我们可以直接获取该m长度的数据即可,这里主要要处理一下\r\n

将命令构建RESP报文规范,根据拆解反操作就可以了,这里暂不介绍了。

上述,我们核心功能已经探讨完毕了。

功能实现

代码已经编写完毕,放置在了gitee上: gitee

如上我们已经学会了如何拆解和组装RESP协议了,我们接着来看,我们如何用go来编写拆解和组装协议的代码呢? 我们可以看。

我们先创建一个字符,然后将其封装为bufio.Reader,我们来看下:

因为我们要使用readLine()函数,所以我们需要将其转换为bufio.Reader类型,若是直接从net.Conn中获取,不用转换,直接可以使用 bufio.Reader的。

我们将上述伪代码编写一下,实现拆解的功能。

其具体执行过程是我们先获取一行数据,放置到data中,而后判断其前缀是什么,若是*则取其后面的数据,将其转为int类型n,而后再递归该函数n次,而后中遇到$,我们则取后面的数据,也是将其转为int类型m,而后再取m长度的实际数据,这就是我们的命令了,最后我们再踢掉命令的\r\n即可。

其中,有一个函数是byteToInt是我们自己写的通过切片转为数字的函数,我们看下

该函数主要的功能是将其[]byte数字转换为int数据。

如上,我们整个RESP协议功能写完了,我们运行下看下实际效果:

Obviously, we successfully disassembled the data.

In this article, we introduce how to use go to simply disassemble the contents of the RESP protocol. Why don’t we introduce how to write redisWhat about master-slave middleware?

At first I planned to write it like this, but with too much knowledge, the introduction will be very complicated and it is difficult to explain one point clearly, so we have chosen a core point to introduce separately. I would like to call it It is called core-oriented programming (my friend told me a long time ago). The so-called simplicity of core-oriented programming means that when we are involved in a function, we must learn to dismantle the function and use the core function first. demo Make it, and then slowly enrich the surroundings to complete the entire requirement package.

Finally, let’s talk about the RESP protocol. The official website summarizes it as simple implementation, quick analysis,direct Can read . If you study these two articles carefully, you will definitely have a deep understanding of this.

Recommended learning: Redis video tutorial

The above is the detailed content of Detailed explanation of Redis RESP protocol implementation examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software