22import pickle
33from typing import Any , Union , Optional
44
5- from aioredis . commands import ContextRedis
5+
66from async_property import async_property
7+ from redis .asyncio import Redis , ConnectionPool
78
89from privex .helpers .common import empty
910
1617# if plugin.HAS_ASYNC_REDIS:
1718from privex .helpers .plugin import get_redis_async , close_redis_async
1819from privex .helpers .cache .asyncx .base import AsyncCacheAdapter
19- import aioredis
20+ from redis import asyncio as aioredis
2021import logging
2122
2223log = logging .getLogger (__name__ )
@@ -85,8 +86,8 @@ class AsyncRedisCache(AsyncCacheAdapter):
8586 adapter_enter_reconnect : bool = True
8687 adapter_exit_close : bool = True
8788
88- _redis_conn : Optional [Union [aioredis .Redis , aioredis . ConnectionsPool ]]
89- _redis : Optional [ContextRedis ]
89+ _redis_conn : Optional [Union [aioredis .Redis , ConnectionPool ]]
90+ _redis : Optional [Redis ]
9091
9192 def __init__ (self , use_pickle : bool = None , redis_instance : aioredis .Redis = None , * args , ** kwargs ):
9293 """
@@ -137,7 +138,10 @@ async def get(self, key: str, default: Any = None, fail: bool = False) -> Any:
137138 async def set (self , key : str , value : Any , timeout : Optional [int ] = DEFAULT_CACHE_TIMEOUT ):
138139 r : aioredis .Redis = await self .redis
139140 v = pickle .dumps (value ) if self .use_pickle else value
140- return await r .set (str (key ), v , expire = timeout )
141+ if timeout :
142+ return await r .setex (str (key ), time = timeout , value = v )
143+ else :
144+ return await r .set (str (key ), v )
141145
142146 # async def get_or_set(self, key: str, value: VAL_FUNC_CORO, timeout: int = DEFAULT_CACHE_TIMEOUT) -> Any:
143147 # return await self.get_or_set_async(key=key, value=value, timeout=timeout)
@@ -162,7 +166,7 @@ async def update_timeout(self, key: str, timeout: int = DEFAULT_CACHE_TIMEOUT) -
162166 await self .set (key = key , value = v , timeout = timeout )
163167 return v
164168
165- async def connect (self , * args , ** kwargs ) -> ContextRedis :
169+ async def connect (self , * args , ** kwargs ) -> Redis :
166170 if not self ._redis_conn :
167171 self ._redis_conn = await get_redis_async ()
168172 if not self ._redis :
@@ -172,10 +176,8 @@ async def connect(self, *args, **kwargs) -> ContextRedis:
172176 async def close (self ):
173177 if self ._redis is not None :
174178 log .debug ("Closing AsyncIO Redis instance %s._redis" , self .__class__ .__name__ )
175- self ._redis .close ()
179+ await self ._redis .aclose ()
176180 self ._redis = None
177- # Closing the Redis connection directly from this method usually leads to problems...
178- # It's safest to just set it to None and then call close_redis_async()
179181 if self ._redis_conn is not None :
180182 log .debug ("Clearing AsyncIO Redis connection pool %s._redis_conn" , self .__class__ .__name__ )
181183 self ._redis_conn = None
0 commit comments