The practice of Redis Pub/sub (subscription and publishing) in Java

Source: Internet
Author: User
Tags redis stub redis server
1. What is Pub/sub

Pub/sub function (means Publish, Subscribe) is the publishing and subscription function. In an event-based system, 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 systems: subscribers (such as clients) express an event or a class of events that it is interested in receiving by means of event subscriptions; publishers such as Server You can notify the relevant subscriber of events of interest to the Subscriber at any time. Friends who are familiar with design patterns should understand that this is very similar to the Observer pattern in 23 design patterns.
Similarly, Redis's pub/sub is a message traffic pattern, with the main purpose of decoupling the message Publisher from the message Subscriber, Redis as a pub/sub server that serves as a message route between the Subscriber and the publisher. realization of 2.Redis pub/sub

Redis the ability to subscribe and publish through the Publish and subscribe commands. Subscribers can subscribe to Redis server by subscribe the message types they are interested in. Redis the type of information as a channel (channel). When a publisher sends a specific type of information to Redis server through the Publish command, all Subscribers subscribing to that message type receive this message.

Client 1 Subscription CCTV1:

127.0.0.1:6379> Subscribe CCTV1
Reading Messages ... (Press Ctrl-c to quit)
1) "Subscribe"
2) "CCTV1"
3) (integer) 1

Client 2 Subscribe to CCTV1 and CCTV2:

127.0.0.1:6379> Subscribe CCTV1 CCTV2
Reading messages ... (Press Ctrl-c to quit)
1 "Subscribe"
2) "CCTV1"
3) (integer) 1
1) "Subscribe"
2) "CCTV2"
3) (integer) 2

The two clients now listen to the specified channel, respectively. Now another client pushes information about the two channels to the server.

127.0.0.1:6379> Publish CCTV1 "CCTV1 is Good"
(integer) 2
//Return 2 indicates that two clients have received the secondary message. The client that is received the message is shown below.
1) "Message"
2) "CCTV1"
3 "" Cctv1 Be Good "
----
1)" Message "
2)" CCTV1 "
3" "CCTV1 is Good"

Subscriptions/publications such as on are also called subscriptions published to the channel (using the Publish and subscribe commands), in addition to subscription publishing to mode (using Psubscribe to subscribe to a pattern)

Subscribe to all CCTV channels

127.0.0.1:6379> psubscribe cctv*
Reading messages ... (Press Ctrl-c to quit)
1) "Psubscribe"
2) "cctv*"
3) (integer) 1

When a CCTV1 message is still pushed first, the client receives it normally.

The implementation of Pub/sub in Java:

Import Redis Driver:

dependencies {
    compile ' redis.clients:jedis:2.4.2 '
}

The Redis driver package provides an abstract class: Jedispubsub ... Inheriting this class completes the monitoring of the subscription to the client. Sample code:

public class Testpubsub extends Jedispubsub {@Override public void OnMessage (string channel, String message) {
    TODO auto-generated Method Stub System.out.println (channel + "," + message); @Override public void Onpmessage (string pattern, string channel, String message) {//TODO Auto-generat

    Ed method Stub System.out.println (pattern + "," + Channel + "," + message); @Override public void Onsubscribe (String channel, int subscribedchannels) {//TODO auto-generated Meth  OD stub System.out.println ("onsubscribe:channel[" + Channel + "]," + "subscribedchannels[" + Subscribedchannels +
    "]"); @Override public void Onunsubscribe (String channel, int subscribedchannels) {//TODO auto-generated Me Thod stub System.out.println ("onunsubscribe:channel[" + Channel + "]," + "subscribedchannels["
    + Subscribedchannels + "]"); } @Override public void OnpUnsubscribe (String pattern, int subscribedchannels) {//TODO auto-generated method stub System.out.printl

    N ("onpunsubscribe:pattern[" + pattern + "]," + "subscribedchannels[" + Subscribedchannels + "]"); @Override public void Onpsubscribe (String pattern, int subscribedchannels) {System.out.println ("onpsub

    scribe:pattern["+ pattern +"], "+" subscribedchannels["+ Subscribedchannels +" ");
 }
}

As shown above, there are six methods in the abstract class. A callback (Onpmessage) that is heard when the subscription mode receives a message (onMessage) is heard when the callback (Onsubscribe) of the subscription channel when the Subscriber receives the message (the callback () is canceled (onunsubscribe) subscription channel mode Callback (Onpsubscribe) when canceling subscription mode (onpunsubscribe)

Run the class we just wrote:

@Test public
    void Pubsubjava () {
        //TODO auto-generated method Stub
        Jedis jr = null;
        try {       
        Jr = new Jedis ("127.0.0.1", 6379, 0);//Redis service address and port number
            Jr.auth ("wx950709");
            Testpubsub sp = new testpubsub ();
            The JR client configuration listens for two channel
            Sp.subscribe (Jr.getclient (), "News.share", "News.blog");
        } catch (Exception e) {
            E.printstacktrace ();
        } finally{
            if (jr!=null) {
                jr.disconnect ();
            }
        }
    }

It's not hard to see from the code that a Redis link we've declared can perform some actions after setting up a listener, such as posting a message, subscribing to a message, etc.
When the above code is run, it is output in the console:

ONSUBSCRIBE:CHANNEL[NEWS.SHARE],SUBSCRIBEDCHANNELS[1]
onsubscribe:channel[news.blog],subscribedchannels[2]
//onsubscribe Method runs successfully

At this point, the OnMessage method can be new.share when a client publish a message to the New.blog channel. (Jedis.publish (channel, message)).

The practice of pub/sub in spring
Import dependent jar

dependencies {
    compile ' org.springframework.data:spring-data-redis:1.7.2.release '
    compile ' redis.clients: jedis:2.4.2 '
}

Links to spring configuration Redis:

@Configuration public class AppConfig {@Bean jedisconnectionfactory jedisconnectionfactory () {Jedisconne
        Ctionfactory jedisconnectionfactory = new Jedisconnectionfactory ();
        Jedisconnectionfactory.setpassword ("xxxx");
    return jedisconnectionfactory; } @Bean redistemplate<string, object> redistemplate () {final redistemplate<string, object> t
        Emplate = new redistemplate<string, object> ();
        Template.setconnectionfactory (Jedisconnectionfactory ());
        Template.setdefaultserializer (New Stringredisserializer ());
    return template; @Bean messagelisteneradapter MessageListener () {return new Messagelisteneradapter (new redismessagelist
    Ener ()); } @Bean Redismessagelistenercontainer Rediscontainer () {Final Redismessagelistenercontainer container =

        New Redismessagelistenercontainer ();
        Container.setconnectionfactory (Jedisconnectionfactory ()); Container. Addmessagelistener (MessageListener (), topic ());
    return container;
    @Bean Redispublisherimpl Redispublisher () {return new Redispublisherimpl (Redistemplate (), topic ());
    @Bean channeltopic Topic () {return new Channeltopic ("Pubsub:queue");
 }

}

A link to Redis is configured as above. Information such as the IP port is not set in Redistemplate is all default. The channeltopic is added to the IOC container in the configuration class. A channel, or Pubsub:queue, is set in a redistemplate (a link to redis) when spring starts.
In the configuration above, Redismessagelistener is what we generate, this class is the core listening class, and Redistemplate accepts how the data is handled in that class.

public class Redismessagelistener implements MessageListener {
        @Override public
        void OnMessage (Final message Message, Final byte[] mode {
            System.out.println ("message Received:" + message.tostring ());
        }

Now we're getting redistemplate and giving Pubsub:queue this channel publish data.

public class Pubsubmain {

    redistemplate<string,object> redistemplate;

    Public  Void Execute () {
       String channel = "Pubsub:queue";
      Redistemplate.convertandsend (channel, "from TestData");
    }
    public static void Main (string[] args) {
        applicationcontext applicationcontext   = new Annotationconfigapplicationcontext (appconfig.class);
        Pubsubmain Pubsubmain = new Pubsubmain ();
        Pubsubmain.redistemplate = (redistemplate<string, object>) Applicationcontext.getbean ("RedisTemplate");
        Pubsubmain.execute ();
    }

Run the main method at this time:

Message Received:from app
///Indicates acceptance success and can still print message on client when starting a client at the command line and publish

The following article will cover more about Redis usage scenarios.

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.