I. Introduction of the Scene
A recent project needs to use the Publish/Subscribe information system to inform the latest real-time messages. After finding out that Redis pub/sub (information system for publish/subscribe) can meet my development needs, and the cost of learning and use is also relatively low.
Two. What is Redis pub/sub
Data View
Everyone is watching my blog at the same time can open the Redis official Redis pub/sub Introduction, feel the English document difficult to read
, you can look at the translation of the Redis Chinese web.
Pub/sub function (means Publish, Subscribe) is the Publish and subscribe function
In 1> event-based systems, Pub/sub is a widely used communication model that uses events as a basic communication mechanism to provide loosely coupled interaction patterns required by large-scale systems: subscribers (such as clients) express an event or class of events that they are interested in receiving, in the form of an event subscription; publisher (such as a server) can notify the relevant subscribers of events of interest to the Subscriber at any time.
2> the message publisher, the publish client, without an exclusive link, you can use the same redis-client link for other operations at the same time publish the message (for example: INCR, etc.)
3> the message subscriber, the Subscribe client, needs an exclusive link, that is, during subscribe, redis-client cannot be interspersed with other operations, when the client waits for the "publish" message in a blocking manner; Therefore, the subscribe side needs to use a separate link, even if it needs to be used in an extra thread.
Three. Basic use of Redis Pub sub (publish subscribe)
Below I will be equipped with a picture (using my local machine environment) to explain how Redis pub/sub to use.
Do not install Phpredis extension or no Redis service, please refer to my other blog, there are detailed installation introduction, here no longer repeat.
1. Start Redis Server:
2. Start Subscribe Client
Open a new terminal, start the Redis client, and as a subscribe client (message subscriber), subscribe to the channel information of a channel named test:
3. Start Publish Client
Start the Redis client as a publish client (the message publisher) and publish a channel named Test with the message: Hello,world
4. View subscribed messages
Then switch to the Redis client window in step 2, and you will find that you have subscribed to the ' Hello,world ' message that was just released:
Code word is not easy, hope reprint annotated source ha