2021-06-28 09:08:09 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
import aioredis
|
2021-08-09 18:57:08 +00:00
|
|
|
# from aioredis import ConnectionsPool
|
2021-06-28 09:08:09 +00:00
|
|
|
|
|
|
|
from settings import REDIS_URL
|
|
|
|
|
|
|
|
|
|
|
|
class Redis:
|
|
|
|
def __init__(self, uri=REDIS_URL):
|
|
|
|
self._uri: str = uri
|
2021-08-09 18:57:08 +00:00
|
|
|
self._instance = None
|
2021-06-28 09:08:09 +00:00
|
|
|
|
|
|
|
async def connect(self):
|
2021-08-09 18:57:08 +00:00
|
|
|
if self._instance is not None:
|
2021-06-28 09:08:09 +00:00
|
|
|
return
|
2021-08-09 18:57:08 +00:00
|
|
|
self._instance = await aioredis.from_url(self._uri)# .create_pool(self._uri)
|
2021-06-28 09:08:09 +00:00
|
|
|
|
|
|
|
async def disconnect(self):
|
2021-08-09 18:57:08 +00:00
|
|
|
if self._instance is None:
|
2021-06-28 09:08:09 +00:00
|
|
|
return
|
2021-08-09 18:57:08 +00:00
|
|
|
self._instance.close()
|
|
|
|
await self._instance.wait_closed()
|
|
|
|
self._instance = None
|
2021-06-28 09:08:09 +00:00
|
|
|
|
|
|
|
async def execute(self, command, *args, **kwargs):
|
2021-08-09 18:57:08 +00:00
|
|
|
return await self._instance.execute(command, *args, **kwargs, encoding="UTF-8")
|
2021-06-28 09:08:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def test():
|
|
|
|
redis = Redis()
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
await redis.connect()
|
|
|
|
await redis.execute("SET", "1-KEY1", 1)
|
|
|
|
await redis.execute("SET", "1-KEY2", 1)
|
|
|
|
await redis.execute("SET", "1-KEY3", 1)
|
|
|
|
await redis.execute("SET", "1-KEY4", 1)
|
|
|
|
await redis.execute("EXPIREAT", "1-KEY4", int(datetime.utcnow().timestamp()))
|
|
|
|
v = await redis.execute("KEYS", "1-*")
|
|
|
|
print(v)
|
|
|
|
await redis.execute("DEL", *v)
|
|
|
|
v = await redis.execute("KEYS", "1-*")
|
|
|
|
print(v)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
import asyncio
|
|
|
|
|
|
|
|
asyncio.run(test())
|