Jedis implementing the Publish subscription feature

Source: Internet
Author: User

Redis provides us with the Publish/subscribe (Publish/subscribe) feature. We can subscribe a channel (a subscription), and Redis notifies us when someone publish a message on the channel so we can get a message from someone else.
As a Redis client for Java, Jedis provides an interface for Publish/subscribe. This article describes how to use Jedis to implement Publish/subscribe for Redis. Defining the Subscriber Class

Jedis defines an abstract class, in which the JedisPubSub callback method of the publish/subsribe is defined. By inheriting the JedisPubSub classes and re-implementing the callback methods, we can customize our own processing logic when the Publish/subsribe event occurs.

In the following example, we define the Subscriber class, which inherits the class and JedisPubSub re-implements the callback method in it.

ImportRedis.clients.jedis.JedisPubSub; Public classSubscriberextendsjedispubsub { PublicSubscriber () {} Public voidOnMessage (String channel, String message) {System.out.println (String.Format ("receive Redis published message, channel%s, message%s", channel, message)); } Public voidOnsubscribe (String Channel,intSubscribedchannels) {System.out.println (String.Format ("Subscribe Redis Channel success, channel%s, subscribedchannels%d", channel, Subscribedchannels)); } Public voidOnunsubscribe (String Channel,intSubscribedchannels) {System.out.println (String.Format ("unsubscribe Redis channel, channel%s, subscribedchannels%d", channel, Subscribedchannels)); }}
Defining the Subthread Thread class

Since the operation of the Jedis subscribe is blocked, we have another thread to perform the subscribe operation.

ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool; Public classSubthreadextendsThread {Private FinalJedispool Jedispool;Private FinalSubscriber subscriber =NewSubscriber ();Private FinalString channel = "MyChannel"; PublicSubthread (Jedispool jedispool) {Super("Subthread"); This. Jedispool = Jedispool; } @Override Public voidRun () {System.out.println (String.Format ("Subscribe Redis, channel%s, thread would be blocked", channel)); Jedis Jedis =NULL;Try{Jedis = Jedispool.getresource ();        Jedis.subscribe (subscriber, channel); }Catch(Exception e) {System.out.println (String.Format ("subsrcibe Channel error,%s", e)); }finally{if(Jedis! =NULL) {jedis.close (); }        }    }}

In the above code, we JedisPool get an instance from Jedis and use the Jedis operation of this instance subscribe .
Jedis's subscribe statement is as follows:

 Public void Subscribe (finalfinal String ... channels)

The first parameter accepts an JedisPubSub object, and the second parameter specifies which channel to subscribe to. In the example above, we pass the object we define to the Subscriber subscribe method.
When the Publish/subscribe event occurs, our method is automatically called Subscriber . Defining the Publisher Class

PublisherClass accepts input from the user and publishes the input to the channel. When the user enters "quit", the input ends.

ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool; Public classPublisher {Private FinalJedispool Jedispool; PublicPublisher (Jedispool jedispool) { This. Jedispool = Jedispool; } Public voidStart () {BufferedReader reader =NewBufferedReader (NewInputStreamReader (system.in)); Jedis Jedis = Jedispool.getresource (); while(true) {String line =NULL;Try{line = Reader.readline ();if(!"quit". Equals (line)) {Jedis.publish ("MyChannel", line); }Else{ Break; }            }Catch(IOException e)            {E.printstacktrace (); }         }    }}

Defining the entry Code

Here is our program entry code.

ImportRedis.clients.jedis.JedisPool;ImportRedis.clients.jedis.JedisPoolConfig; Public classPubsubdemo { Public Static voidMain (string[] args) {//Replace with your Reids address and portString Redisip = "192.168.229.154";intReidsport = 6379; Jedispool Jedispool =NewJedispool (NewJedispoolconfig (), Redisip, Reidsport); System.out.println (String.Format ("Redis Pool is starting, Redis IP%s, redis port%d", Redisip, Reidsport)); Subthread Subthread =NewSubthread (Jedispool);        Subthread.start (); Publisher publisher =NewPublisher (Jedispool);    Publisher.start (); }}

In the above code, we first generated a JedisPool Redis connection pool, which is thread-safe because it is Jedis not thread-safe JedisPool . And our program in the main thread and the subscription thread (subthread) need to use Jedis , so in the program we use JedisPool . You can also refer to using Jedis in a multithreaded environment.
Since Jedis the subcribe operation is blocked, we have another thread to perform the subcribe operation.
By invoking the Publisher::start() method, the user's input is accepted and publish to the specified channel. Output

Redis pool is starting, Redis IP 192.168.229.154, redis port 6379
Subscribe Redis, channel MyChannel, thread'll be blocked
Subscribe Redis channel Success, Channel MyChannel, Subscribedchannels 1

This input

Hello

Output in control window

Receive Redis published message, channel MyChannel, message hello

Resources
    • Https://github.com/xetorthio/jedis/wiki/AdvancedUsage
    • http://basrikahveci.com/a-simple-jedis-publish-subscribe-example/

Jedis implementing the Publish subscription feature

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.