Redis 发布订阅

11 篇文章 1 订阅
Redis 发布订阅
Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息

举一个实例

# 第一步,创建订阅频道为redisChat
127.0.0.1:6379> subscribe redisChat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1

# 第二步,在重新开启一个redis客户端,然后在同一频道redisChat发布两次消息,订阅者能接收到消息
127.0.0.1:6379> publish redisChat "Redis is a great caching technique"
(integer) 1
127.0.0.1:6379> publish redisChat "Learn redis by runoob.com"
(integer) 1

# 第三步,订阅者客户端会展示如下消息
1) "message"
2) "redisChat"
3) "Redis is a great caching technique"
1) "message"
2) "redisChat"
3) "Learn redis by runoob.com"

psubscribe pattern [pattern…]

描述:命令订阅一个或多个符合给定模式的频道,每个模式以*作为匹配符,比如it*匹配所有以it开头的频道(it.news, it.blog,it.tweets等等)。new.*匹配所有以new.开头的频道(news.it,news.global.today等等)

返回值:接收到的消息

# 订阅mychannel频道
127.0.0.1:6379> psubscribe mychannel
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "mychannel"
3) (integer) 1

pubsub subcommand [argument [argument]]

描述:pubsub 命令用于查看订阅与发布系统状态,它由数个不同格式的子命令组成

返回值:由活跃频道组成的列表

127.0.0.1:6379> pubsub channels
(empty list or set)

publish channel message

描述:用于将信息发送到指定的频道

返回值:接收到信息的订阅者数量

# 将 "hello, i am here" 发送到频道mychannel
127.0.0.1:6379> publish mychannel "hello, i am here"
(integer) 1
# 客户端订阅了mychannel接收到数据
127.0.0.1:6379> psubscribe mychannel
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "mychannel"
3) (integer) 1
1) "pmessage"
2) "mychannel"
3) "mychannel"
4) "hello, i am here"

subscribe channel [channel …]

描述:用于订阅给定的一个或多个频道的信息

返回值:接收到的信息

127.0.0.1:6379> subscribe mychannel
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "mychannel"
3) (integer) 1
1) "message"
2) "mychannel"
3) "test"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值