redis-multi-exec-fix-6
This commit is contained in:
parent
4de7c9fe1b
commit
29478aa04b
|
@ -1,5 +1,5 @@
|
|||
sentry-sdk
|
||||
aredis
|
||||
redis[hiredis]
|
||||
ariadne
|
||||
starlette
|
||||
uvicorn
|
||||
|
|
|
@ -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):
|
||||
|
|
Loading…
Reference in New Issue
Block a user