66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
import asyncio
|
|
import aioredis
|
|
from settings import REDIS_URL
|
|
|
|
|
|
class RedisCache:
|
|
def __init__(self, uri=REDIS_URL):
|
|
self._uri: str = uri
|
|
self.pubsub_channels = []
|
|
self._redis = None
|
|
|
|
async def connect(self):
|
|
pool = aioredis.ConnectionPool.from_url(
|
|
self._uri, encoding="utf-8", max_connections=10
|
|
)
|
|
self._redis = aioredis.Redis(connection_pool=pool)
|
|
|
|
async def disconnect(self):
|
|
await self._redis.wait_closed()
|
|
self._redis = None
|
|
|
|
async def execute(self, command, *args, **kwargs):
|
|
while not self._redis:
|
|
await asyncio.sleep(1)
|
|
try:
|
|
print("[redis] " + command + " " + " ".join(args))
|
|
return await self._redis.execute_command(command, *args, **kwargs)
|
|
except Exception:
|
|
pass
|
|
|
|
async def execute_pubsub(self, command, *args, **kwargs):
|
|
while not self._redis:
|
|
await asyncio.sleep(1)
|
|
try:
|
|
print("[redis] " + command + " " + " ".join(args))
|
|
return await self._redis.execute_pubsub(command, *args, **kwargs)
|
|
except Exception:
|
|
pass
|
|
|
|
async def subscribe(self, *channels):
|
|
if not self._redis:
|
|
await self.connect()
|
|
for channel in channels:
|
|
await self._redis.execute_pubsub("SUBSCRIBE", channel)
|
|
self.pubsub_channels.append(channel)
|
|
|
|
async def unsubscribe(self, *channels):
|
|
if not self._redis:
|
|
return
|
|
for channel in channels:
|
|
await self._redis.execute_pubsub("UNSUBSCRIBE", channel)
|
|
self.pubsub_channels.remove(channel)
|
|
|
|
async def lrange(self, key, start, stop):
|
|
print(f"[redis] LRANGE {key} {start} {stop}")
|
|
return await self._redis.lrange(key, start, stop)
|
|
|
|
async def mget(self, key, *keys):
|
|
print(f"[redis] MGET {key} {keys}")
|
|
return await self._redis.mget(key, *keys)
|
|
|
|
|
|
redis = RedisCache()
|
|
|
|
__all__ = ["redis"]
|