MukeshKapoor25 commited on
Commit
6e5d529
·
1 Parent(s): 05a9234

refactor(cache): improve redis client initialization with better error handling

Browse files

Add connection timeout settings and fallback mechanism for authentication failures
Move client creation to separate function for lazy initialization

Files changed (1) hide show
  1. app/core/cache_client.py +66 -26
app/core/cache_client.py CHANGED
@@ -1,6 +1,6 @@
1
  import logging
2
  from redis.asyncio import Redis
3
- from redis.exceptions import RedisError
4
  from app.core.config import settings
5
 
6
  logger = logging.getLogger(__name__)
@@ -9,31 +9,71 @@ logger = logging.getLogger(__name__)
9
  CACHE_HOST, CACHE_PORT = settings.CACHE_URI.split(":")
10
  CACHE_PORT = int(CACHE_PORT)
11
 
12
- try:
13
- # Configure Redis client based on whether password is provided and not empty
14
- if settings.CACHE_K and settings.CACHE_K.strip():
15
- redis_client = Redis(
16
- host=CACHE_HOST,
17
- port=CACHE_PORT,
18
- username="default",
19
- password=settings.CACHE_K,
20
- decode_responses=True
21
- )
22
- logger.info(f"Connected to Redis at {CACHE_HOST}:{CACHE_PORT} with authentication")
23
- else:
24
- # Local Redis without authentication
25
- redis_client = Redis(
26
- host=CACHE_HOST,
27
- port=CACHE_PORT,
28
- decode_responses=True
29
- )
30
- logger.info(f"Connected to Redis at {CACHE_HOST}:{CACHE_PORT} without authentication")
31
- except RedisError as e:
32
- logger.error(f"Failed to connect to Redis: {e}")
33
- raise
34
- except Exception as e:
35
- logger.error(f"Unexpected error connecting to Redis: {e}")
36
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  async def get_redis() -> Redis:
 
 
 
39
  return redis_client
 
1
  import logging
2
  from redis.asyncio import Redis
3
+ from redis.exceptions import RedisError, ConnectionError, AuthenticationError
4
  from app.core.config import settings
5
 
6
  logger = logging.getLogger(__name__)
 
9
  CACHE_HOST, CACHE_PORT = settings.CACHE_URI.split(":")
10
  CACHE_PORT = int(CACHE_PORT)
11
 
12
+ async def create_redis_client():
13
+ """Create Redis client with proper error handling and fallback"""
14
+ try:
15
+ # First try with authentication if password is provided
16
+ if settings.CACHE_K and settings.CACHE_K.strip():
17
+ redis_client = Redis(
18
+ host=CACHE_HOST,
19
+ port=CACHE_PORT,
20
+ username="default",
21
+ password=settings.CACHE_K,
22
+ decode_responses=True,
23
+ socket_connect_timeout=5,
24
+ socket_timeout=5,
25
+ retry_on_timeout=True
26
+ )
27
+ # Test the connection
28
+ await redis_client.ping()
29
+ logger.info(f"Connected to Redis at {CACHE_HOST}:{CACHE_PORT} with authentication")
30
+ return redis_client
31
+ else:
32
+ # Try without authentication for local Redis
33
+ redis_client = Redis(
34
+ host=CACHE_HOST,
35
+ port=CACHE_PORT,
36
+ decode_responses=True,
37
+ socket_connect_timeout=5,
38
+ socket_timeout=5,
39
+ retry_on_timeout=True
40
+ )
41
+ # Test the connection
42
+ await redis_client.ping()
43
+ logger.info(f"Connected to Redis at {CACHE_HOST}:{CACHE_PORT} without authentication")
44
+ return redis_client
45
+
46
+ except AuthenticationError as e:
47
+ logger.warning(f"Authentication failed for Redis: {e}")
48
+ # Try without authentication as fallback
49
+ try:
50
+ redis_client = Redis(
51
+ host=CACHE_HOST,
52
+ port=CACHE_PORT,
53
+ decode_responses=True,
54
+ socket_connect_timeout=5,
55
+ socket_timeout=5,
56
+ retry_on_timeout=True
57
+ )
58
+ await redis_client.ping()
59
+ logger.info(f"Connected to Redis at {CACHE_HOST}:{CACHE_PORT} without authentication (fallback)")
60
+ return redis_client
61
+ except Exception as fallback_error:
62
+ logger.error(f"Redis fallback connection also failed: {fallback_error}")
63
+ raise
64
+
65
+ except ConnectionError as e:
66
+ logger.error(f"Failed to connect to Redis at {CACHE_HOST}:{CACHE_PORT}: {e}")
67
+ raise
68
+ except Exception as e:
69
+ logger.error(f"Unexpected error connecting to Redis: {e}")
70
+ raise
71
+
72
+ # Initialize Redis client
73
+ redis_client = None
74
 
75
  async def get_redis() -> Redis:
76
+ global redis_client
77
+ if redis_client is None:
78
+ redis_client = await create_redis_client()
79
  return redis_client