Java实现Redis的消息订阅和发布
Redis的订阅和发布原理可以查看资料:
http://doc.redisfans.com/pub_sub/pubsub.html#pubsub-channels-pattern
下面我就用java简单实现一下:
源码地址:
http://download.csdn.net/detail/admin1973/9769527
需要导入包:
1.编写监听:
package com.leitao.threadsync.redispub;
import redis.clients.jedis.JedisPubSub;
/**
* Created by leitao on 2017/3/3.
*/
public class RedisMsgPubSubListener extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
System.out.println("channel:" + channel + "receives message :" + message);
//this.unsubscribe();//取消订阅
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
System.out.println("channel:" + channel + "is been subscribed:" + subscribedChannels);
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
System.out.println("channel:" + channel + "is been unsubscribed:" + subscribedChannels);
}
}
2.订阅者
package com.leitao.threadsync.redispub;
import redis.clients.jedis.Jedis;
/**
* Created by leitao on 2017/3/3.
*/
public class TestSubscribe {
public static void main(String[] args){
Jedis jedis = new Jedis("localhost");
RedisMsgPubSubListener listener = new RedisMsgPubSubListener();
/**
* 注意:subscribe是一个阻塞的方法,在取消订阅该频道前,会一直阻塞在这,只有当取消了订阅才会执行下面的other code,
* 参考上面代码,我在onMessage里面收到消息后,调用了this.unsubscribe(); 来取消订阅,这样才会执行后面的other code
*/
jedis.subscribe(listener, "redisChat");
//如果没有取消订阅,方法将一直堵塞在此处不会向下执行
//to do others
}
}
3.发布者
package com.leitao.threadsync.redispub;
import redis.clients.jedis.Jedis;
/**
* Created by leitao on 2017/3/3.
*/
public class TestPublish {
public static void main(String[] args) throws Exception{
Jedis jedis = new Jedis("localhost");
jedis.publish("redisChat", "Redis is a great caching technique");
Thread.sleep(5000);
jedis.publish("redisChat", "build your dream");
Thread.sleep(5000);
jedis.publish("redisChat", "over");
}
}
运行:
先启动订阅者,再启动发布者,控制台打印
=完=