I. Introduction to REDIS Publishing subscriptions
A publish Subscription (PUB/SUB) is a message communication pattern that is primarily designed to decouple the coupling between a message publisher and a message subscriber. Pub/sub not only solves the direct code-level coupling between publishers and subscribers, but also solves the coupling between the two on physical deployments.
Two. Test source 1. Start Redis 2 first. Release
Create a new Java Project, and then create a new class to add the main method to the Redis publishing message:
Package Com.luych.message.publish; Import Redis.clients.jedis.Jedis; Public class App { publicstaticvoid main (string[] args) { New Jedis ("127.0.0.1", 6379); Jedis.publish ("Channel1", "hello!" ); Jedis.publish ("Channel2", "How does you do!" ); Jedis.close (); }}
3. Subscription
Create a new Java Project, and then create a new class that inherits Jedispubsub:
Package Com.luych.message.subscribe; Import Redis.clients.jedis.JedisPubSub; Public class extends jedispubsub { @Override publicvoid onMessage (String channel, String Message) { System.out.println ("received message from" + Channel + ", Message content:" + message ); Super . OnMessage (channel, message);} }
The OnMessage method, which is the method to execute when a subscription message is received.
Create a new class and add the main method to the Redis subscription message:
Package Com.luych.message.subscribe; Import Redis.clients.jedis.Jedis; Public class App { publicstaticvoid main (string[] args) { New Jedis ("127.0.0.1", 6379); Jedis.subscribe (new Subscriber (), "Channel1", "Channel2"); Jedis.close (); }}
4. Test run
First, running the Subscriber (run as Java application), you can see that when the main process executes to jedis.subscribe, the process is blocked, into the message listening state.
Then, run the publishing side (run as Java application), and after the publisher code execution finishes, you can see that the console has printed the results.
Received the message from CHANNEL1, message content: hello! do do!
Three. Post-language
The above example is very simple, but you can see the advantage of Redis in publishing subscriptions. Pub/sub not only solves the direct code-level coupling between publishers and subscribers, but also solves the coupling between the two in physical deployment. As a pub/sub server, Redis serves as a message routing feature between subscribers and publishers. Subscribers can subscribe to Redis server with the Subscribe command for the type of message they are interested in, and Redis calls the message type channel. When a publisher sends a specific type of message to Redis server through the Publish command. All clients subscribing to this message type receive this message. The delivery of the message here is many-to-many. A client can subscribe to multiple channel, or it can send messages to multiple channel.
Redis (4)----Publish a subscription