search
HomeDatabaseRedisRedis study notes publish and subscribe

This article brings you relevant knowledge about Redis, which mainly introduces issues related to publish and subscribe. Redis publish and subscribe (pub/sub) is a message communication mode: send The publisher (pub) sends the message, and the subscriber (sub) receives the message. Let's take a look at it. I hope it will be helpful to everyone.

Redis study notes publish and subscribe

Recommended learning: Redis video tutorial

Redis publish and subscribe (pub/sub) is a message communication model : The sender (pub) sends the message, and the subscriber (sub) receives the message.

Redis clients can subscribe to any number of channels.

Subscribe/publish message graph:

The first object: the message sender. Second object: channel. The third object: message subscriber.

Redis study notes publish and subscribe

The following figure shows the relationship between channel channel1 and the three clients that subscribe to this channel - client2, client5 and client1:

Redis study notes publish and subscribe

When a new message is sent to channel channel1 through the PUBLISH command, this message will be sent to the three clients that subscribe to it:

Redis study notes publish and subscribe

Command Description
Publish channel message Command Send the message to specified channel.
SUBSCRIBE channel [channel …] Subscribe to the information of one or more given channels.
UNSUBSCRIBE channel [channel …] refers to unsubscribing from a given channel.
[PUNSUBSCRIBE pattern [pattern …]] Unsubscribe from all channels of the given pattern.
[PUBSUB argument [argument …] View the subscription and publishing system status.
PSUBSCRIBE pattern [pattern …] Subscribe to one or more channels that match the given pattern.

Test

Subscriber:

127.0.0.1:6379> subscribe mianbao 			# 订阅频道 mianbao
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "mianbao"
3) (integer) 1
# 等待读取推送的消息
1) "message"		# 消息
2) "mianbao"		# 频道
3) "hello"			# 消息内容
1) "message"
2) "mianbao"
3) "hello redis"

Sender:

127.0.0.1:6379> publish mianbao "hello"			# 发送消息到频道		
(integer) 1
127.0.0.1:6379> publish mianbao "hello redis"
(integer) 1

Principle:

Redis is implemented using C. By analyzing the pubsub.c file in the Redis source code, we can understand the underlying implementation of the publishing and subscription mechanism, and deepen our understanding of Redis.

Redis implements publishing and subscribing functions through commands such as PUBLISH, SUBSCRIBE and PSUBSCRIBE.

After subscribing to a channel through the SUBSCRIBE command, a dictionary is maintained in redis-server. The keys of the dictionary are channels, and the value of the dictionary is a linked list. All subscriptions are stored in the linked list. The client of the channel. The key to the SUBSCRIBE command is to add the client to the subscription list of a given channel.

Send a message to the subscriber through the PUBLISH command. The redis-server will use the given channel as the key, search the linked list of all clients that subscribe to this channel in the channel dictionary it maintains, and traverse the linked list. , publish the message to all subscribers.

Pub/Sub literally means publishing (Publish) and subscription (Subscribe). In Redis, you can set up message publishing and message subscription for a certain key value. When a key value is used, After a message is published, all clients that subscribe to it will receive the corresponding message. The most obvious use of this function is as a real-time messaging system, such as ordinary instant chat, group chat and other functions.


For slightly more complex scenarios we will use message middleware: RabbitMQ, RocketMQ, ActiveMQ, kafka

Recommended learning: Redis video tutorial

The above is the detailed content of Redis study notes publish and subscribe. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. 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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

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.