Phpredispubsub message subscription I. scenario introduction
A publish/subscribe information system is required for a recent project to implement notifications of the latest real-time messages. After searching, we found that redis pub/sub (publish/subscribe information system) can meet my development needs, and the learning and usage costs are relatively low.
II. what is redis pub/sub?
While reading my blog, you can open the official redis introduction to redis pub/sub. if you have a hard time reading the English document
For more information, see the translation of redis Chinese network.
Pub/Sub (means Publish, Subscribe) is the Publish and Subscribe function.
1> in an event-based system, Pub/Sub is a widely used communication model. it uses events as the basic communication mechanism to provide a loosely coupled interaction mode required by large-scale systems: A subscriber (such as a client) subscribes to an event to express an event or a type of event that it is interested in receiving. a publisher (such as a server) can notify relevant subscriber of the event of interest to the subscriber at any time.
2> the message publisher, that is, the publish client, does not require an exclusive link. you can use the same redis-client link to perform other operations (such as INCR) while publishing a publish message)
3> the message subscriber, that is, the subscribe client, must have an exclusive link. during The subscribe process, the redis-client cannot be interspersed with other operations. in this case, the client waits for the message of the "publish end" in a blocking manner; this is easy to understand, so the subscribe end needs to use a separate link, or even in an additional thread.
III. basic usage of redis pub sub (publish subscribe) I will provide a real image (using my local machine environment) to explain how to use redis pub/sub.
If the phpredis extension is not installed or the redis service is not available, please refer to my other blog for detailed installation introduction. I will not go into details here.
1. start the redis server:
2. start the subscribe client.
Open a new terminal, start the redis client, and subscribe to the channel information of a channel named test as the subscribe client (message subscriber:
3. start the publish client
Start the redis client and use it as the publish client (message publisher) to publish a channel named test. The message is hello, world.
4. View subscribed messages
Switch to the redis client window in step 2 and you will find that you have subscribed to the 'Hello, world' message just published:
It is not easy to use the code word.