public class TestPubSub extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
// TODO Auto-generated method stub
System.out.println(channel + "," + message);
throw new IllegalStateException("exit pubsub");
}
@Override
public void onPMessage(String pattern, String channel, String message) {
// TODO Auto-generated method stub
System.out.println(pattern + "," + channel + "," + message);
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
System.out.println("onSubscribe: channel[" + channel + "]," + "subscribedChannels[" + subscribedChannels + "]");
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
System.out.println(
"onUnsubscribe: channel[" + channel + "], " + "subscribedChannels[" + subscribedChannels + "]");
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
// TODO Auto-generated method stub
System.out.println("onPUnsubscribe: pattern[" + pattern + "]," +
"subscribedChannels[" + subscribedChannels + "]");
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.println("onPSubscribe: pattern[" + pattern + "], " +
"subscribedChannels[" + subscribedChannels + "]");
}
}
public class RedisPubSubTest {
@Test
public void test() {
// TODO Auto-generated method stub
Jedis jr = null;
try {
jr = new Jedis("127.0.0.1", 6379, 0);// redis服务地址和端口号
TestPubSub sp = new TestPubSub();
// jr客户端配置监听两个channel
String channel1 = "news.share";
String channel2 = "news.blog";
jr.subscribe(sp, channel1, channel2);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jr != null) {
jr.disconnect();
}
}
}
}