redis的pub/sub
代码:
sub:
import redis import json from redis import Redis, ConnectionPool def jsonStandFormat(jsondata): return json.dumps(jsondata, sort_keys=True, indent=4, separators=(',', ':'), ensure_ascii=False) # 连接到Redis if 0: r = redis.Redis(host='localhost', port=6379, db=0) else: pool = ConnectionPool(host='localhost', port=6379, db=0, max_connections=10) r = Redis(connection_pool=pool) # 订阅频道 pubsub = r.pubsub() pubsub.subscribe('news') # 订阅以'news_'开头的所有频道 pubsub.psubscribe('news.*') # 监听并打印收到的消息 for message in pubsub.listen(): for k,v in message.items(): message[k] = v.decode() if type(v) == bytes else v if message['type'] == 'message': #print(jsonStandFormat(message)) print(f"频道[{message['channel']}]: {message['data']}") if message['type'] == 'pmessage': #print(jsonStandFormat(message)) print(f"频道[{message['channel']}]: {message['data']}") pubsub.unsubscribe()
pub:
import redis from redis import Redis, ConnectionPool import random # 连接到Redis if 0: r = redis.Redis(host='localhost', port=6379, db=0) else: pool = ConnectionPool(host='localhost', port=6379, db=0, max_connections=10) r = Redis(connection_pool=pool) # 发布消息到频道 r.publish('news', '这是我的消息%s' % random.randint(1,999)) r.publish('news.%s' % random.randint(1,999), '这是我的消息%s' % random.randint(1,999))
测试情况:

本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/18891701

浙公网安备 33010602011771号