Redis 的 SUBSCRIBE 命令能够让客户端订阅任意数量的频道,每当有新信息发送到被订阅的频道时, 信息就会被发送给全部订阅指定频道的客户端。
做为例子, 下图展现了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:python
当有新消息经过 PUBLISH 命令发送给频道channel1 时, 这个消息就会被发送给订阅它的三个客户端:redis
2 example 实例演示
发布端:this
# -*- coding: UTF-8 -*- import redis redis_client = redis.StrictRedis(host='localhost', port=6379, db=0) # 创建PubSub对象订阅通道和侦听新消息 p = redis_client.pubsub() # 订阅两个频道,分别是my-first-channel,和my-second-channel p.subscribe('my-first-channel', 'my-second-channel') # 使用publish推送消息,注意是StrictRedis类的方法 redis_client.publish('my-first-channel', 'nihvdfdao')
订阅端A:spa
# -*- coding: UTF-8 -*- import redis redis_server = redis.StrictRedis(host='localhost', port=6379, db=0) # 创建PubSub对象订阅通道和侦听新消息 p = redis_server.pubsub() # 订阅两个频道,分别是my-first-channel,和my-second-channel p.subscribe('my-first-channel', 'my-second-channel') # 使用p.listen()方法监听频道 for item in p.listen(): # 若是订阅的频道存储的项目是'message' if item['type'] == 'message': # 则打印这个项目 print item['data']
订阅端B:orm
# -*- coding: UTF-8 -*- import redis redis_server = redis.StrictRedis(host='localhost', port=6379, db=0) # 创建PubSub对象订阅通道和侦听新消息 p = redis_server.pubsub() # 订阅两个频道,分别是my-first-channel,和my-second-channel p.subscribe('my-first-channel', 'my-second-channel') whileTrue: data =msg_queue.parse_response() print pickle.loads(data[2])
redis 命令:server
订阅:对象
SUBSCRIBE fm_105blog
发布:图片
PUBLISH fm_105 "this is fm_105"
本文部份内容和图片引用如下网址:
http://zc985552943.iteye.com/blog/2037535