redis 发布 订阅 java demo

2018-01-24

72

0

技术:redis-x64-3.2.100 + java8

运行环境:IDEA 15.2 + jdk8 + windows 7

demo功能:提供一个redis发布订阅的基本java demo

核心发布订阅代码

public class RedisMsgPubSubListener extends JedisPubSub {
    @Override
    public void unsubscribe() {
        super.unsubscribe();
    }
    @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:" + channel + "receives message :" + message);
    }
    @Override
    public void onPMessage(String pattern, String channel, String message) {

    }
    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("channel:" + channel + "is been subscribed:" + subscribedChannels);
    }
    @Override
    public void onPUnsubscribe(String pattern, int subscribedChannels) {

    }
    @Override
    public void onPSubscribe(String pattern, int subscribedChannels) {

    }
    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println("channel:" + channel + "is been unsubscribed:" + subscribedChannels);
    }
}

测试

先执行下面这个main 函数, 代表订阅一个频道。 执行后, 线程是被hold住的。

public class SubMain {
    public static void main(String[] arsg) {
        Jedis jedis = new Jedis("localhost", 6379);
        RedisMsgPubSubListener listener = new RedisMsgPubSubListener();
        jedis.subscribe(listener, "redisChatTest");
    }
}

再执行一个发布main函数,代表在已订阅的频道中发布消息

public class PubMain {
    public static void main(String[] arsg) throws InterruptedException {
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.publish("redisChatTest", "这个是我发送的消息");
        Thread.sleep(5000);
        jedis.publish("redisChatTest", "你收到没有");
        Thread.sleep(5000);
        jedis.publish("redisChatTest", "哈哈");
    }
}

 

 

 
 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

youlixishi

自己选择的路, 风雨兼程