订阅者
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('*********') #发送的内容
网友评论