11from typing import Mapping , Optional , Union
22
33from errors import RedisConnectionError
4- from redis .asyncio import Redis
4+ from redis .asyncio import ConnectionPool , Redis
55
66
77class RedisClient :
@@ -13,11 +13,11 @@ def __init__(self, redis_url: str) -> None:
1313
1414 :param redis_url: Redis URL to connect.
1515 """
16- self .redis_client = Redis .from_url (redis_url )
16+ self .redis_pool = ConnectionPool .from_url (redis_url )
1717
1818 async def close (self ) -> None :
1919 """Closes redis connection."""
20- await self .redis_client . close ()
20+ await self .redis_pool . disconnect ()
2121
2222 async def hset (
2323 self ,
@@ -33,7 +33,8 @@ async def hset(
3333 :raises RedisConnectionError: if redis is not available.
3434 """
3535 try :
36- await self .redis_client .hset (name , mapping = mapping )
36+ async with Redis (connection_pool = self .redis_pool ) as redis :
37+ await redis .hset (name , mapping = mapping )
3738 except ConnectionError as exc :
3839 raise RedisConnectionError ("Redis is unavailable" ) from exc
3940
@@ -49,7 +50,8 @@ async def hget(self, name: str, key: str) -> Optional[bytes]:
4950 :returns: bytes.
5051 """
5152 try :
52- return await self .redis_client .hget (name = name , key = key )
53+ async with Redis (connection_pool = self .redis_pool ) as redis :
54+ return await redis .hget (name = name , key = key )
5355 except ConnectionError as exc :
5456 raise RedisConnectionError ("Redis is unavailable" ) from exc
5557
@@ -64,6 +66,7 @@ async def exists(self, name: str) -> bool:
6466 :returns: True if name exists else False
6567 """
6668 try :
67- return bool (await self .redis_client .exists (name ))
69+ async with Redis (connection_pool = self .redis_pool ) as redis :
70+ return bool (await redis .exists (name ))
6871 except ConnectionError as exc :
6972 raise RedisConnectionError ("Redis is unavailable" ) from exc
0 commit comments