1. First you need a message listener class
Package com.sogou.baike.testimport.testSubscribe;
Import Redis.clients.jedis.JedisPubSub;
/** * Created by Denglinjie on 2016/6/29. */public class Redismsgpubsublistener extends Jedispubsub {@Override public void unsubscribe () {super.u
Nsubscribe ();
@Override public void unsubscribe (String ... channels) {super.unsubscribe (channels);
@Override public void Subscribe (String ... channels) {super.subscribe (channels);
@Override public void Psubscribe (String ... patterns) {super.psubscribe (patterns);
@Override public void Punsubscribe () {super.punsubscribe ();
@Override public void Punsubscribe (String ... patterns) {super.punsubscribe (patterns); @Override public void OnMessage (string channel, String message) {SYSTEM.OUT.PRINTLN ("channel:" + Chann
El + "receives message:" + message);
This.unsubscribe ();
} @Override public void Onpmessage (string pattern, string channel, String message) {} @Override public void Onsubscrib E (String channel, int subscribedchannels) {System.out.println ("Channel: + Channel +" is been subscribed: "+ Subs
Cribedchannels); @Override public void Onpunsubscribe (String pattern, int subscribedchannels) {} @Override Public void Onpsubscribe (string pattern, int subscribedchannels) {} @Override public void Onunsubscribe (String ch Annel, int subscribedchannels) {System.out.println ("channel:" + Channel + "is been unsubscribed:" + Subscribedcha
Nnels);
}
}
The class needs to inherit jedispubsub and implement its abstract method, which is clearly seen by the name of the method, which is used to subscribe to a channel, to subscribe to the channel, to unsubscribe, to receive messages, and so on, to call the relevant method
2. Subscribe to test class
public class Testsubscribe {
@Test public
void Testsubscribe () throws exception{
Jedis Jedis = new Jedis ("Loc Alhost ");
Redismsgpubsublistener listener = new Redismsgpubsublistener ();
Jedis.subscribe (Listener, "redischattest");
Other code
}
}
This class realizes to the channel Redischattest subscription listens, the channel's subscription, cancels the subscription, receives the message to call the Listener object the corresponding method
Note: Subscribe is a blocking method that will block until you unsubscribe from the channel, and only if you cancel the subscription will execute the following other code, refer to the above codes, I received the message in OnMessage, I called This.unsubscribe ( ); To cancel the subscription so that other code is executed later
3. Release message test class
public class Testpublish {
@Test public
void Testpublish () throws exception{
Jedis Jedis = new Jedis ("Localho St ");
Jedis.publish ("Redischattest", "I am a Genius");
Thread.Sleep (5000);
Jedis.publish ("Redischattest", "I'm Cool");
Thread.Sleep (5000);
Jedis.publish ("Redischattest", "haha");
}
This class publishes a message to the channel Redischattest, and the second step is to receive the message because the channel is subscribed to.