# _*_ coding: utf-8 _*_"""Python操作Redis实现消息的发布与订阅"""import sysimport timeimport redis# 全局变量conn_pool = redis.ConnectionPool(host="localhost", port=6379, db=1)conn_inst = redis.Redis(connection_pool=conn_pool)channel_name = "fm-101.1"def public_test():while True:# 发布消息conn_inst.publish(channel_name, "hello " + str(time.time()))if int(time.time()) % 10 == 1:conn_inst.publish(channel_name, "over")time.sleep(1)def subscribe_test(_type=0):pub = conn_inst.pubsub()pub.subscribe(channel_name)if _type == 0:# 订阅消息for item in pub.listen():print("Listen on channel: %s" % item)if item["type"] == "message" and item["data"].decode() == "over":print(item["channel"].decode(), "已停止发布")breakelse:# 另一种订阅模式while True:item = pub.parse_response()print("Listen on channel: %s" % item)if item[0].decode() == "message" and item[2].decode() == "over":print(item[1].decode(), "已停止发布")break# 取消订阅pub.unsubscribe()returnif __name__ == '__main__':if sys.argv[1] == "public":public_test()else:subscribe_test(int(sys.argv[2]))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。