inbox/services/redis.py

62 lines
1.9 KiB
Python
Raw Normal View History

2023-10-13 09:40:33 +00:00
import redis.asyncio as aredis
2023-10-03 14:15:17 +00:00
from settings import REDIS_URL
2023-10-14 06:38:12 +00:00
2023-10-03 14:15:17 +00:00
class RedisCache:
def __init__(self, uri=REDIS_URL):
self._uri: str = uri
self.pubsub_channels = []
2023-10-13 09:40:33 +00:00
self._client = None
2023-10-03 14:15:17 +00:00
async def connect(self):
2023-10-13 09:40:33 +00:00
self._client = aredis.Redis.from_url(self._uri, decode_responses=True)
2023-10-03 14:15:17 +00:00
async def disconnect(self):
2023-10-13 16:45:30 +00:00
if self._client:
await self._client.close()
2023-10-03 14:15:17 +00:00
async def execute(self, command, *args, **kwargs):
2023-10-13 16:45:30 +00:00
if self._client:
try:
print("[redis] " + command + " " + " ".join(args))
r = await self._client.execute_command(command, *args, **kwargs)
return r
except Exception as e:
print(f"[redis] error: {e}")
2023-10-13 09:33:31 +00:00
return None
2023-10-03 14:15:17 +00:00
async def subscribe(self, *channels):
2023-10-13 16:45:30 +00:00
if self._client:
async with self._client.pubsub() as pubsub:
for channel in channels:
await pubsub.subscribe(channel)
self.pubsub_channels.append(channel)
2023-10-03 14:15:17 +00:00
async def unsubscribe(self, *channels):
2023-10-13 09:40:33 +00:00
if not self._client:
2023-10-03 14:15:17 +00:00
return
2023-10-13 09:40:33 +00:00
async with self._client.pubsub() as pubsub:
2023-10-13 09:33:31 +00:00
for channel in channels:
await pubsub.unsubscribe(channel)
self.pubsub_channels.remove(channel)
2023-10-03 14:15:17 +00:00
2023-10-04 21:20:43 +00:00
async def publish(self, channel, data):
2023-10-13 09:40:33 +00:00
if not self._client:
2023-10-04 21:20:43 +00:00
return
2023-10-13 09:40:33 +00:00
await self._client.publish(channel, data)
2023-10-04 21:20:43 +00:00
2023-10-03 14:15:17 +00:00
async def lrange(self, key, start, stop):
2023-10-13 16:45:30 +00:00
if self._client:
print(f"[redis] LRANGE {key} {start} {stop}")
return await self._client.lrange(key, start, stop)
2023-10-03 14:15:17 +00:00
async def mget(self, key, *keys):
2023-10-13 16:45:30 +00:00
if self._client:
print(f"[redis] MGET {key} {keys}")
return await self._client.mget(key, *keys)
2023-10-03 14:15:17 +00:00
2023-10-14 06:38:12 +00:00
2023-10-03 14:15:17 +00:00
redis = RedisCache()
__all__ = ["redis"]