Redis Data Summary (vi) Publish subscription

Source: Internet
Author: User
Tags redis server

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, which is similar to the observer pattern in design patterns. Pub/sub not only solves the direct code level coupling between publishers and subscribers, but also solves the coupling between the two on the 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 and Psubscribe commands 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.

Let's do an experiment. Here are two different clients, one of which is Redis's own redis-cli and the other is a simple client written in Java. The code is as follows

1234567891011121314151617181920212223242526 import java.io.*;import java.net.*;public class PubSubTest {    public static void main(String[] args) {        String cmd = args[0] + "\r\n";        try {            Socket socket = new Socket("192.168.56.55", 6379);            InputStream in = socket.getInputStream();            OutputStream out = socket.getOutputStream();            out.write(cmd.getBytes());             //发送订阅命令            byte[] buffer = new byte[1024];            while (true) {                int readCount = in.read(buffer);                System.out.write(buffer, 0, readCount);                System.out.println("--------------------------------------");            }        } catch (Exception e) {        }    }}

The code simply reads the incoming subscription command from the command line, sends it to REDIS server through a socket connection, and then goes into the while loop and reads the message that Redis server is sending over the subscription. and print to the console
1 Compile and run this Java program first (I'm running under Win7)

D:\>javac Pubsubtest.java
D:\>java Pubsubtest "Subscribe
News.share
News.blog "
*
$9
Subscribe
$
News.share
: 1
*
$9
Subscribe
$9
News.blog
: 2

--------------------------------------
2 Start REDIS-CLI

redis> Psubscribe news.*
Reading messages ... (Press
Ctrl-c to quit)
1. "Psubscribe"
2. "News.*"
3. (integer) 1

3 Restart a redis-cli to post two messages

redis> Publish News.share "share a link
Http://www.google.com "
(integer) 2
Redis> Publish
News.blog "I post a blog"
(integer) 2

4. View the output of the two subscription client
The Java client now prints the following:

*
$7
Message
$
News.share
$34
Share a link
http://www.google.com
--------------------------------------
*
$7
Message
$9
News.blog
$13
I
Post a blog

--------------------------------------
Another REDIS-CLI output is as follows

1. "Pmessage"
2. "News.*"
3. "News.share"
4. "Share a link
Http://www.google.com "
1. "Pmessage"
2. "News.*"
3. "News.blog"
4.
"I post a blog"

Analysis under

The Java client subscribes to the News.share and News.blog two channels using the Subscribe command, and then immediately receives the subscription success message returned by the server, and you can see that the Redis protocol is of the text type, which does not explain the specific protocol content. You can refer to the Http://redis.io/topics/protocol person http://terrylee.me/blog/post/2011/01/26/redis-internal-part3.aspx. This message content has two parts, the first part indicates that the socket connection on the use of Subscribe subscription news.share successful, this connection subscription channel number is 1, the latter part indicates that the use of Subscribe subscription News.blog successful, the total number of the connection subscription channel is 2.

The Redis client uses Psubscribe to subscribe to a channel that uses wildcards (* denotes any string), and this subscription receives all the channel messages that match the news.*. REDIS-CLI A subscription success message that is printed to the console indicates that the total number of connection subscription channels is 1 after a successful subscription with the Psubscribe command news.*.
After we send two messages to the News.share and News.blog channels in a client using publish. The Redis returned (integer) 2 indicates that two connections received this message. You can verify the output of two subscribers by observing them. The specific format does not explain, are relatively simple.

After reading a small example should have a perceptual understanding of the Pub/sub function. It is important to note that when a connection is subscribed to a channel via subscribe or psubscribe, it enters the subscription mode. In this mode, other commands can no longer be sent in addition to subscribing to additional channels or exiting the subscription mode with the unsubscribe or Punsubscribe command. In addition, using the Psubscribe command to subscribe to multiple wildcard channels, if a message matches multiple channel patterns, the same message is received multiple times.

Jredis the current version does not provide pub/sub support, but it should be quite simple to implement one yourself. The entire application can share the same connection. Because the message messages returned by Redis include message-related channel information in addition to the message content itself, when the message is received it can be processed according to different channel information to call different callback.

Another person thinks that Redis's pub/sub is still a little too thin (implementation only uses 150 lines of code). In safety, certification, reliability this convenience is not much support.

Redis Data Summary (vi) Publish subscription

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.