redis发布与订阅

使用连接池

pub.py
import redis


message_list = 'abcedfghigklmn'
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True)
rc = redis.StrictRedis(connection_pool=pool, socket_timeout=0.5, decode_responses=True,socket_keepalive=True, retry_on_timeout=True, db=5)
for message in message_list:
    rc.publish("my_channel", message)   # 发布消息到指定 channel
sub.py
import redis

# 这里需要在定义connectionpool时候指定decode_reponse=True, 否则解析到的所有消息均会为bytes类型
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True)
rc = redis.StrictRedis(connection_pool=pool, socket_timeout=0.5, decode_responses=True,socket_keepalive=True, retry_on_timeout=True, db=5)
ps = rc.pubsub()
ps.subscribe('my_channel')  # 从my_channel订阅消息
for item in ps.listen():  # 监听状态:有消息发布了就拿过来
    if item['type'] == 'message':
        print(item['channel'])
        print(item['data'])

decode_responses=True 参数作用

# 不指定
"""
b'my_channel'
b'a'
b'my_channel'
b'b'
b'my_channel'
b'c'
b'my_channel'
b'e'
b'my_channel'
b'd'
b'my_channel'
b'f'
b'my_channel'
b'g'
b'my_channel'
b'h'
b'my_channel'
b'i'
b'my_channel'
b'g'
b'my_channel'
b'k'
b'my_channel'
b'l'
b'my_channel'
b'm'
b'my_channel'
b'n'
"""
# 指定
"""
my_channel
a
my_channel
b
my_channel
c
my_channel
e
my_channel
d
my_channel
f
my_channel
g
my_channel
h
my_channel
i
my_channel
g
my_channel
k
my_channel
l
my_channel
m
my_channel
n
"""
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容