1
1
from typing import Mapping , Optional , Union
2
2
3
3
from errors import RedisConnectionError
4
- from redis .asyncio import Redis
4
+ from redis .asyncio import ConnectionPool , Redis
5
5
6
6
7
7
class RedisClient :
@@ -13,11 +13,11 @@ def __init__(self, redis_url: str) -> None:
13
13
14
14
:param redis_url: Redis URL to connect.
15
15
"""
16
- self .redis_client = Redis .from_url (redis_url )
16
+ self .redis_pool = ConnectionPool .from_url (redis_url )
17
17
18
18
async def close (self ) -> None :
19
19
"""Closes redis connection."""
20
- await self .redis_client . close ()
20
+ await self .redis_pool . disconnect ()
21
21
22
22
async def hset (
23
23
self ,
@@ -33,7 +33,8 @@ async def hset(
33
33
:raises RedisConnectionError: if redis is not available.
34
34
"""
35
35
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 )
37
38
except ConnectionError as exc :
38
39
raise RedisConnectionError ("Redis is unavailable" ) from exc
39
40
@@ -49,7 +50,8 @@ async def hget(self, name: str, key: str) -> Optional[bytes]:
49
50
:returns: bytes.
50
51
"""
51
52
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 )
53
55
except ConnectionError as exc :
54
56
raise RedisConnectionError ("Redis is unavailable" ) from exc
55
57
@@ -64,6 +66,7 @@ async def exists(self, name: str) -> bool:
64
66
:returns: True if name exists else False
65
67
"""
66
68
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 ))
68
71
except ConnectionError as exc :
69
72
raise RedisConnectionError ("Redis is unavailable" ) from exc
0 commit comments