2022-09-18 22:11:26 +00:00
|
|
|
from aioredis import from_url
|
2022-11-23 09:57:58 +00:00
|
|
|
from asyncio import sleep
|
2022-09-17 18:12:14 +00:00
|
|
|
from settings import REDIS_URL
|
|
|
|
|
|
|
|
|
2022-09-18 22:11:26 +00:00
|
|
|
class RedisCache:
|
2022-09-17 18:12:14 +00:00
|
|
|
def __init__(self, uri=REDIS_URL):
|
|
|
|
self._uri: str = uri
|
|
|
|
self._instance = None
|
|
|
|
|
|
|
|
async def connect(self):
|
|
|
|
if self._instance is not None:
|
|
|
|
return
|
2022-09-18 22:11:26 +00:00
|
|
|
self._instance = await from_url(self._uri, encoding="utf-8")
|
2022-11-25 22:35:42 +00:00
|
|
|
# print(self._instance)
|
2022-09-17 18:12:14 +00:00
|
|
|
|
|
|
|
async def disconnect(self):
|
|
|
|
if self._instance is None:
|
|
|
|
return
|
2022-09-19 13:50:43 +00:00
|
|
|
await self._instance.close()
|
2022-09-18 22:11:26 +00:00
|
|
|
# await self._instance.wait_closed() # deprecated
|
2022-09-17 18:12:14 +00:00
|
|
|
self._instance = None
|
|
|
|
|
|
|
|
async def execute(self, command, *args, **kwargs):
|
2022-11-23 09:57:58 +00:00
|
|
|
while not self._instance:
|
|
|
|
await sleep(1)
|
2022-11-25 22:35:42 +00:00
|
|
|
try:
|
2023-10-10 13:37:28 +00:00
|
|
|
# print("[redis] " + command + ' ' + ' '.join(args))
|
2022-11-25 22:35:42 +00:00
|
|
|
return await self._instance.execute_command(command, *args, **kwargs)
|
|
|
|
except Exception:
|
|
|
|
pass
|
2022-09-17 18:12:14 +00:00
|
|
|
|
|
|
|
async def lrange(self, key, start, stop):
|
2023-10-10 13:37:28 +00:00
|
|
|
# print(f"[redis] LRANGE {key} {start} {stop}")
|
2022-09-17 18:12:14 +00:00
|
|
|
return await self._instance.lrange(key, start, stop)
|
|
|
|
|
|
|
|
async def mget(self, key, *keys):
|
2023-10-10 13:37:28 +00:00
|
|
|
# print(f"[redis] MGET {key} {keys}")
|
2022-09-17 18:12:14 +00:00
|
|
|
return await self._instance.mget(key, *keys)
|
|
|
|
|
|
|
|
|
2022-09-18 22:11:26 +00:00
|
|
|
redis = RedisCache()
|
2022-09-17 18:12:14 +00:00
|
|
|
|
|
|
|
__all__ = ["redis"]
|