notifier/services/rediscache.py

76 lines
2.2 KiB
Python
Raw Normal View History

2024-02-16 23:56:15 +00:00
import asyncio
2023-11-26 19:36:02 +00:00
import json
2024-02-16 23:56:15 +00:00
import logging
2023-11-26 11:54:07 +00:00
2023-11-23 22:58:55 +00:00
import redis.asyncio as aredis
2024-02-16 23:56:15 +00:00
2023-11-23 22:58:55 +00:00
from settings import REDIS_URL
2024-01-23 14:52:12 +00:00
2024-02-16 23:56:15 +00:00
logger = logging.getLogger('\t[services.redis]\t')
2024-01-23 14:52:12 +00:00
logger.setLevel(logging.DEBUG)
2023-11-23 22:58:55 +00:00
2024-02-04 04:58:44 +00:00
2023-11-23 22:58:55 +00:00
class RedisCache:
def __init__(self, uri=REDIS_URL):
self._uri: str = uri
self.pubsub_channels = []
self._client = None
async def connect(self):
self._client = aredis.Redis.from_url(self._uri, decode_responses=True)
async def disconnect(self):
if self._client:
await self._client.close()
async def execute(self, command, *args, **kwargs):
if self._client:
try:
2024-02-16 23:56:15 +00:00
logger.debug(command + ' ' + ' '.join(args))
2023-11-23 22:58:55 +00:00
r = await self._client.execute_command(command, *args, **kwargs)
return r
except Exception as e:
2024-02-16 23:56:15 +00:00
logger.error(f'{e}')
2023-11-23 22:58:55 +00:00
return None
async def subscribe(self, *channels):
if self._client:
async with self._client.pubsub() as pubsub:
for channel in channels:
await pubsub.subscribe(channel)
self.pubsub_channels.append(channel)
async def unsubscribe(self, *channels):
if not self._client:
return
async with self._client.pubsub() as pubsub:
for channel in channels:
await pubsub.unsubscribe(channel)
self.pubsub_channels.remove(channel)
async def publish(self, channel, data):
if not self._client:
return
await self._client.publish(channel, data)
2023-12-22 09:09:03 +00:00
async def listen(self, pattern):
2023-11-26 19:36:02 +00:00
if self._client:
pubsub = self._client.pubsub()
2023-12-22 09:09:03 +00:00
await pubsub.psubscribe(pattern)
2023-11-26 11:54:07 +00:00
2023-11-26 19:39:08 +00:00
while True:
message = await pubsub.get_message()
2024-02-16 23:56:15 +00:00
if message and isinstance(message['data'], (str, bytes, bytearray)):
logger.debug('pubsub got msg')
2023-11-26 19:41:33 +00:00
try:
2024-02-16 23:56:15 +00:00
yield json.loads(message['data']), message.get('channel')
2023-12-22 09:09:03 +00:00
except Exception as e:
2024-02-16 23:56:15 +00:00
logger.error(f'{e}')
2023-12-23 18:21:40 +00:00
await asyncio.sleep(1)
2023-11-26 11:54:07 +00:00
2023-11-23 22:58:55 +00:00
redis = RedisCache()
2024-02-16 23:56:15 +00:00
__all__ = ['redis']