redis发送订阅

订阅者

shanghaimei@shanghaimei:~$ redis-cli
127.0.0.1:6379> SUBSCRIBE wechat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "wechat"
3) (integer) 1

发送者

127.0.0.1:6379> PUBLISH wechat "hello!"
(integer) 1
127.0.0.1:6379> PUBLISH wechat "Nice to meet you!"
(integer) 1

订阅者

1) "message"
2) "wechat"
3) "hello!"
1) "message"
2) "wechat"
3) "Nice to meet you!"

python实现 (help类)

import redis

class RedisHelper:
    def __init__(self):
        self.__conn = redis.Redis(host='********')
        self.chan_sub = 'test'
        self.chan_pub= 'test'

#发送消息
    def public(self,msg):
        self.__conn.publish(self.chan_pub,msg)
        return True
#订阅
    def subscribe(self):
        #打开收音机
        pub = self.__conn.pubsub()
        #调频道
        pub.subscribe(self.chan_sub)
        #准备接收
        pub.parse_response()
        return pub

订阅者

from  redishelper import RedisHelper
obj = RedisHelper()
redis_sub = obj.subscribe()

while True:
    msg = redis_sub.parse_response()
    print('接收:',msg)

发布者

from  redishelper import RedisHelper
obj = RedisHelper()
obj.public('*********') #发送的内容

原文地址:https://www.cnblogs.com/gaizhongfeng/p/8109982.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 数据流的传输过程, 就是订阅者角色的交接过程 ,数据由新的交接者进行传递。就像是接驳, 一条流水线上, 数据从 ...
    我是小胡胡123阅读 1,645评论 0 2
  • 订阅、取消订阅和发布实现了发布/订阅的消息范式,在这种范式下,发送方(发布者)没有被编程为将他们的消息发送给特定的...
    shysheng阅读 297评论 0 1
  • 本文主要说明Redis中发布与订阅功能的设计与实现。 I、上帝视角看发布于订阅 Redis主要通过PUBLISH,...
    wenmingxing阅读 628评论 0 1
  • redis-订阅与发布 Redis 通过 PUBLISH 、 SUBSCRIBE 等命令实现了订阅与发布模式, 这...
    全能程序猿阅读 5,864评论 0 4
  • 翻旧电脑的硬盘,看到了之前一位姑娘在我一份文档中写下的劝我开心的话语,很想她 在很长的一段时间里一直以一副阴暗的状...
    牧野边阅读 293评论 0 0