Publish and subscribe for redis

The so-called publish-subscribe is actually a producer-consumer model:

As shown above: the publisher publishes the message to the channel, and then the subscriber subscribes to the channel. In this way, every time the publisher publishes a message to the corresponding channel, all the subscribers who subscribe to the channel will receive the message (Note: If a new subscriber subscribes to the channel, then it cannot receive historical messages, i.e. messages previously published by the channel)

Related API

publish [channel message] --- publish a message to the channel channel, the return value is the number of subscribers.

subscribe [channel...] ​​--- Subscribe to channel(s) and return information about the corresponding channel

unsubscribe [channel...] ​​--- Cancel one or more subscriptions

psubscribe [pattern...] --- Subscribe by pattern, such as what letter to subscribe to.

punsubscribe [pattern...] --- Unsubscribe from the specified pattern.

pubsub channels --- List channels with at least one subscriber.

pubsub numsub [channel...] ​​--- List the number of subscribers for a given channel

pubsub numpat [pattern...] --- List the number of subscribed patterns

The difference between publish and subscribe and message queue

Both publish and subscribe and message queues are producer-consumer models. The difference between them is that when a message publisher publishes a message, all subscribers of the publish and subscribe (subscribing to the channel) will receive the corresponding message. The message queue is a feature of grabbing, that is, only one consumer can get the message. Redis does not provide a function called message queue, but we can use the data structure of list to implement a message queue with lpush and brpop.

So how to choose message queue or publish and subscribe?

For example: 1. If we need to delete the local cache of all subscribers at the same time, in this scenario, we can use publish and subscribe, because they can all receive messages, so as to clear the local cache 2. If it is a red packet grab queue, then You can use a message queue, as long as one consumer gets it, it's ok.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325473708&siteId=291194637
Recommended