redis-multi-exec-fix-6

This commit is contained in:
Untone 2023-10-13 12:33:31 +03:00
parent 4de7c9fe1b
commit 29478aa04b
2 changed files with 15 additions and 23 deletions

View File

@ -1,5 +1,5 @@
sentry-sdk
aredis
redis[hiredis]
ariadne
starlette
uvicorn

View File

@ -1,50 +1,42 @@
import asyncio
import aredis
import redis.asyncio as redis
from settings import REDIS_URL
class RedisCache:
def __init__(self, uri=REDIS_URL):
self._uri: str = uri
self.pubsub_channels = []
self._redis = None
self._pubsub = None
self.loop = asyncio.get_event_loop()
async def connect(self):
self._redis = aredis.StrictRedis.from_url(self._uri, decode_responses=True, loop=self.loop)
await self._redis.connection_pool.get_connection()
self._pubsub = self._redis.pubsub()
response = await self.execute('PING')
print(f"[redis] PING response: {response}")
self._redis = redis.Redis.from_url(self._uri, decode_responses=True)
async def disconnect(self):
self._redis.connection_pool.re
self._redis = None
self._pubsub = None
await self._redis.aclose()
async def execute(self, command, *args, **kwargs):
while not self._redis:
await asyncio.sleep(1)
if not self._redis:
await self.connect()
try:
print("[redis] " + command + " " + " ".join(args))
return await self._redis.execute_command(command, *args, **kwargs)
except Exception as e:
print(f"[redis] error: {e}")
raise
return None
async def subscribe(self, *channels):
if not self._redis:
await self.connect()
async with self._redis.pubsub() as pubsub:
for channel in channels:
await self._pubsub.subscribe(channel)
await pubsub.subscribe(channel)
self.pubsub_channels.append(channel)
async def unsubscribe(self, *channels):
if not self._redis:
return
async with self._redis.pubsub() as pubsub:
for channel in channels:
await self._pubsub.unsubscribe(channel)
await pubsub.unsubscribe(channel)
self.pubsub_channels.remove(channel)
async def publish(self, channel, data):