Skip to content

Commit 54b30b8

Browse files
committed
Simplify Redis connection with a dynamic client class approach
1 parent 0db3650 commit 54b30b8

File tree

1 file changed

+20
-31
lines changed

1 file changed

+20
-31
lines changed

src/common/connection.py

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import redis
44
from redis import Redis
55
from redis.cluster import RedisCluster
6-
from typing import Optional
6+
from typing import Optional, Type, Union
77
from common.config import REDIS_CFG
88

99
from common.config import generate_redis_uri
@@ -16,36 +16,25 @@ class RedisConnectionManager:
1616
def get_connection(cls, decode_responses=True) -> Redis:
1717
if cls._instance is None:
1818
try:
19-
# Common connection parameters
20-
common_params = {
21-
"host": REDIS_CFG["host"],
22-
"port": REDIS_CFG["port"],
23-
"username": REDIS_CFG["username"],
24-
"password": REDIS_CFG["password"],
25-
"ssl": REDIS_CFG["ssl"],
26-
"ssl_ca_path": REDIS_CFG["ssl_ca_path"],
27-
"ssl_keyfile": REDIS_CFG["ssl_keyfile"],
28-
"ssl_certfile": REDIS_CFG["ssl_certfile"],
29-
"ssl_cert_reqs": REDIS_CFG["ssl_cert_reqs"],
30-
"ssl_ca_certs": REDIS_CFG["ssl_ca_certs"],
31-
"decode_responses": decode_responses,
32-
"lib_name": f"redis-py(mcp-server_v{__version__})"
33-
}
34-
35-
if REDIS_CFG["cluster_mode"]:
36-
# Cluster-specific parameters
37-
cluster_params = {
38-
**common_params,
39-
"max_connections_per_node": 10
40-
}
41-
cls._instance = RedisCluster(**cluster_params)
42-
else:
43-
# Standalone-specific parameters
44-
standalone_params = {
45-
**common_params,
46-
"max_connections": 10
47-
}
48-
cls._instance = redis.Redis(**standalone_params)
19+
# Select the appropriate Redis client class
20+
redis_class: Type[Union[Redis, RedisCluster]] = RedisCluster if REDIS_CFG["cluster_mode"] else redis.Redis
21+
22+
# Create the connection with appropriate parameters
23+
cls._instance = redis_class(
24+
host=REDIS_CFG["host"],
25+
port=REDIS_CFG["port"],
26+
username=REDIS_CFG["username"],
27+
password=REDIS_CFG["password"],
28+
ssl=REDIS_CFG["ssl"],
29+
ssl_ca_path=REDIS_CFG["ssl_ca_path"],
30+
ssl_keyfile=REDIS_CFG["ssl_keyfile"],
31+
ssl_certfile=REDIS_CFG["ssl_certfile"],
32+
ssl_cert_reqs=REDIS_CFG["ssl_cert_reqs"],
33+
ssl_ca_certs=REDIS_CFG["ssl_ca_certs"],
34+
decode_responses=decode_responses,
35+
lib_name=f"redis-py(mcp-server_v{__version__})",
36+
**({"max_connections_per_node": 10} if REDIS_CFG["cluster_mode"] else {"max_connections": 10})
37+
)
4938

5039
except redis.exceptions.ConnectionError:
5140
print("Failed to connect to Redis server", file=sys.stderr)

0 commit comments

Comments
 (0)