如何在订阅频道之前将消息发布到 Redis
How to get messages published to Redis before subscribing to the channel
我正在编写一个应用程序来获取发布到 Redis 中的通道的消息并处理它们。这是一个长期存在的应用程序,基本上从不收听频道。
def msg_handler():
r = redis.client.StrictRedis(host='localhost', port=6379, db=0)
sub = r.pubsub()
sub.subscribe(settings.REDIS_CHANNEL)
while True:
msg = sub.get_message()
if msg:
if msg['type'] == 'message':
print(msg)
def main():
for i in range(3):
t = threading.Thread(target=msg_handler, name='worker-%s' % i)
print('thread {}'.format(i))
t.setDaemon(True)
t.start()
while True:
print('Waiting')
time.sleep(1)
当我 运行 这个程序时,我注意到它没有收到在程序启动之前发布到频道的消息。在应用程序订阅频道后,将消息发送到频道效果很好。
在制作中,很可能在节目开始之前频道中有一些消息。有没有办法获取这些旧消息?
Redis PUB/SUB 不存储已发布的消息。它会将它们发送给此刻正在收听的人。如果您需要访问旧消息,您可以:
- 使用Redis Streams。他们现在处于测试阶段,即将推出版本 5。
- 使用另一个PUBSUB系统,例如nats.io
我正在编写一个应用程序来获取发布到 Redis 中的通道的消息并处理它们。这是一个长期存在的应用程序,基本上从不收听频道。
def msg_handler():
r = redis.client.StrictRedis(host='localhost', port=6379, db=0)
sub = r.pubsub()
sub.subscribe(settings.REDIS_CHANNEL)
while True:
msg = sub.get_message()
if msg:
if msg['type'] == 'message':
print(msg)
def main():
for i in range(3):
t = threading.Thread(target=msg_handler, name='worker-%s' % i)
print('thread {}'.format(i))
t.setDaemon(True)
t.start()
while True:
print('Waiting')
time.sleep(1)
当我 运行 这个程序时,我注意到它没有收到在程序启动之前发布到频道的消息。在应用程序订阅频道后,将消息发送到频道效果很好。
在制作中,很可能在节目开始之前频道中有一些消息。有没有办法获取这些旧消息?
Redis PUB/SUB 不存储已发布的消息。它会将它们发送给此刻正在收听的人。如果您需要访问旧消息,您可以:
- 使用Redis Streams。他们现在处于测试阶段,即将推出版本 5。
- 使用另一个PUBSUB系统,例如nats.io