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 sentry-sdk
aredis redis[hiredis]
ariadne ariadne
starlette starlette
uvicorn uvicorn

View File

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