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
"""

你可能感兴趣的:(redis发布与订阅)