Redis -java 快速实现订阅/发布者模式

334 阅读1分钟

这是我参与更文挑战的第 7 天,活动详情查看

概述

一种消息通信模式。 Redis发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis客户端可以订阅任意数量的频道。
订阅/发布示意图:

image.png

下图展示了频道channel和定义这个频道的三个客户端

image.png

当有新消息通过publish命令发送给频道channel1时,这个消息会被发送给订阅它的三个客户端

image.png

命令

1.PSUBSCRIBE pattern [pattern …]
订阅一个或多个符号给定模式的频道。
2.PUBSUB subcommand [argument [argument …]]
查看订阅与发表系统状态
3.PUBLISH channel message
将信息发送到指定的频道
4.PUNSUBSCRIBE [pattern [pattern…]]
退订所有给定模式的频道
5.SUBSCRIBE channel [channel…]
订阅给定的一个或多个频道的信息
6.UNSUBSCRIBE [channel[channel…]
指退订给定的频道

测试
创建链接

    jedis = new Jedis(redis_ip,redis_prot);
    jedis.auth(redis_pw);

订阅端:

@Test
public void subjava(){
    System.out.println("订阅者 ");
    //为了方便我把redis链接放到了GeoTest
    Jedis jr = GeoTest.jedis;
    jr.select(2);
    try {
        RedisMsgPubSubListenerTest sp = new RedisMsgPubSubListenerTest();
        // jr客户端配置监听两个channel
        jr.subscribe(sp, "news.share", "news.blog");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (jr != null) {
            jr.disconnect();
        }
    }
}

发送端:

@Test
public void pubjava() {
    System.out.println("发布者 ");
    Jedis jr = GeoTest.jedis;
    jr.select(2);
    try {
        // jr客户端配置监听两个channel
        for (int i=0;i<100;i++) {
            Thread.sleep(1000);
            jr.publish("news.share", "新闻分享"+i);
            jr.publish("news.blog", "新闻博客"+i);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (jr != null) {
            jr.disconnect();
        }
    }
}

订阅端:

127.0.0.1:6379> SUBSCRIBE channelTest # 订阅一个频道channelTest
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channelTest"
3) (integer) 1
# 等待推送的信息
1) "message"
2) "channelTest"
3) "hello"
1) "message" # 消息
2) "channelTest" # 频道
3) "world" # 消息内容

发送端:

127.0.0.1:6379> ping
PONG
127.0.0.1:6379> PUBLISH channelTest hello # 发布消息到指定的频道
(integer) 1
127.0.0.1:6379> PUBLISH channelTest world
(integer) 1