platypush/platypush/bus/redis.py

61 lines
1.4 KiB
Python
Raw Normal View History

2018-09-20 09:41:19 +02:00
import logging
import threading
2023-02-05 22:00:50 +01:00
from typing import Optional
2018-09-20 09:41:19 +02:00
from platypush.bus import Bus
from platypush.message import Message
2020-09-27 01:33:38 +02:00
logger = logging.getLogger('platypush:bus:redis')
2018-09-20 09:41:19 +02:00
class RedisBus(Bus):
2023-02-05 22:00:50 +01:00
"""
Overrides the in-process in-memory local bus with a Redis bus
"""
2018-09-20 09:41:19 +02:00
_DEFAULT_REDIS_QUEUE = 'platypush/bus'
2022-01-23 14:25:00 +01:00
def __init__(self, *args, on_message=None, redis_queue=None, **kwargs):
2023-02-05 22:00:50 +01:00
from platypush.utils import get_redis
2023-02-05 22:00:50 +01:00
super().__init__(on_message=on_message)
self.redis = get_redis(*args, **kwargs)
self.redis_args = kwargs
self.redis_queue = redis_queue or self._DEFAULT_REDIS_QUEUE
2018-09-20 09:41:19 +02:00
self.on_message = on_message
self.thread_id = threading.get_ident()
2023-02-05 22:00:50 +01:00
def get(self) -> Optional[Message]:
"""
Reads one message from the Redis queue
"""
2018-09-20 09:41:19 +02:00
try:
if self.should_stop():
2023-02-05 22:00:50 +01:00
return None
msg = self.redis.blpop(self.redis_queue, timeout=1)
if not msg or msg[1] is None:
2023-02-05 22:00:50 +01:00
return None
2021-06-25 22:47:40 +02:00
msg = msg[1].decode('utf-8')
2022-01-23 14:25:00 +01:00
return Message.build(msg)
2018-09-20 09:41:19 +02:00
except Exception as e:
logger.exception(e)
2023-02-05 22:00:50 +01:00
return None
2018-09-20 09:41:19 +02:00
def post(self, msg):
2023-02-05 22:00:50 +01:00
"""
Sends a message to the Redis queue
"""
return self.redis.rpush(self.redis_queue, str(msg))
2018-09-20 09:41:19 +02:00
def stop(self):
super().stop()
self.redis.close()
2018-09-20 09:41:19 +02:00
# vim:sw=4:ts=4:et: