我正在编写一个应用程序来获取发布到 Redis 中的 channel 的消息并对其进行处理。这是一个长期存在的应用程序,基本上从不收听 channel 。
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)
当我运行这个程序时,我注意到它没有收到在程序启动之前发布到 channel 的消息。在应用程序订阅 channel 后,将消息发送到 channel 效果很好。
在生产中,很可能在节目开始之前 channel 中有一些消息。有没有办法获取这些旧消息?
最佳答案
Redis PUB/SUB 不存储已发布的消息。它会将它们发送给此刻正在收听的人。如果您需要访问旧消息,您可以:
- 使用Redis Streams .他们现在处于测试阶段,即将推出第 5 版。
- 使用另一个 PUBSUB 系统,例如 nats.io
关于python - 如何在订阅 channel 之前将消息发布到 Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399438/