Redis 发布订阅消息对列实作(Python)

'''Redis pubsub, subscribe, listen, json.loads'''# pip install redisimport redisimport jsonr = redis.Redis(host="localhost", port=6379, db=1) # connect to redisp = r.pubsub(ignore_subscribe_messages=True) # set pubsub to ignore_subscrible_messages truep.subscribe('topic-1', 'topic-2') # subscrible a topicp.psubscribe('topic-*') # or psubscrible, pattern mode  for message in p.listen(): # listen what you just subscribed    # message is a type of dict, including four keys , type, pattern, channel and data    data = json.loads(message['data']) # extract data     print(type(data), data)
"""Redis publish, json.dumps"""import redisimport jsondb = redis.Redis(host="localhost", port=6379, db=1)dict_data = {"name": "John", "gender": "male"}json_data = json.dumps(dict_data)db.publish("topic-1", json_data)
> {"name": "John", "gender": "male"}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章