Java实现Redis的消息订阅和发布

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");
    }
}
运行:

先启动订阅者,再启动发布者,控制台打印



=完=

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值