2020-04-08 23:22:54 +02:00
|
|
|
import ast
|
2018-09-20 09:41:19 +02:00
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
import threading
|
|
|
|
|
|
|
|
from redis import Redis
|
|
|
|
|
|
|
|
from platypush.bus import Bus
|
2019-02-23 21:19:00 +01:00
|
|
|
from platypush.config import Config
|
2018-09-20 09:41:19 +02:00
|
|
|
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):
|
|
|
|
""" Overrides the in-process in-memory local bus with a Redis bus """
|
|
|
|
_DEFAULT_REDIS_QUEUE = 'platypush/bus'
|
|
|
|
|
|
|
|
def __init__(self, on_message=None, redis_queue=_DEFAULT_REDIS_QUEUE,
|
|
|
|
*args, **kwargs):
|
|
|
|
super().__init__(on_message=on_message)
|
2019-02-23 21:19:00 +01:00
|
|
|
|
|
|
|
if not args and not kwargs:
|
|
|
|
kwargs = (Config.get('backend.redis') or {}).get('redis_args', {})
|
|
|
|
|
2018-09-20 09:41:19 +02:00
|
|
|
self.redis = Redis(*args, **kwargs)
|
2019-02-23 21:19:00 +01:00
|
|
|
self.redis_args = kwargs
|
2018-09-20 09:41:19 +02:00
|
|
|
self.redis_queue = redis_queue
|
|
|
|
self.on_message = on_message
|
|
|
|
self.thread_id = threading.get_ident()
|
|
|
|
|
|
|
|
def get(self):
|
|
|
|
""" Reads one message from the Redis queue """
|
2018-10-25 20:45:58 +02:00
|
|
|
msg = None
|
|
|
|
|
2018-09-20 09:41:19 +02:00
|
|
|
try:
|
|
|
|
msg = self.redis.blpop(self.redis_queue)
|
2020-04-08 23:22:54 +02:00
|
|
|
if not msg or msg[1] is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
msg = msg[1].decode('utf-8')
|
|
|
|
try:
|
|
|
|
msg = json.loads(msg)
|
|
|
|
except json.decoder.JSONDecodeError:
|
|
|
|
msg = ast.literal_eval(msg)
|
|
|
|
|
|
|
|
msg = Message.build(msg)
|
2018-09-20 09:41:19 +02:00
|
|
|
except Exception as e:
|
|
|
|
logger.exception(e)
|
|
|
|
|
|
|
|
return msg
|
|
|
|
|
|
|
|
def post(self, msg):
|
|
|
|
""" Sends a message to the Redis queue """
|
2018-11-20 15:14:59 +01:00
|
|
|
return self.redis.rpush(self.redis_queue, str(msg))
|
2018-09-20 09:41:19 +02:00
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|