您的位置:首页 > 数据库 > Redis

python操作redis进行发布和订阅消息

2018-03-27 10:00 645 查看
在远程服务器安装redis,并启动
订阅端代码
import redis
pool=redis.ConnectionPool(host='192.168.100.30',
port=6379,db=0,
password='123456')
r=redis.StrictRedis(connection_pool=pool)
p=r.pubsub()
p.subscribe("spub","cctv1")
for item in p.listen():
print("Listen on channel : %s "%item['channel'].decode())
if item['type']=='message':
data=item['data'].decode()
print("From %s get message : %s"%(item['channel'].decode(),item['data'].decode()))
if item['data']=='over':
print(item['channel'].decode(),'停止发布')
break
p.unsubscribe('spub')
print("取消订阅")


发布端

import redis
pool=redis.ConnectionPool(host='192.168.100.30',
port=6379,db=0,
password='123456')
r=redis.StrictRedis(connection_pool=pool)
while True:
msg=input("publish: >>")
if msg=="over":
print("停止发布")
break
r.publish('spub',msg)


查看原文:http://www.chenqmc.com/?p=386
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: