File size: 1,176 Bytes
ef1ad9e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# --- Library Imports ---
from fastapi import Depends
from redis import BlockingConnectionPool, Redis
# ---
# --- User Imports ---
from ..app_logger.logger import logger
from ...config.env import env
# ---
# --- Constants ---
# Create a global variable to store the connection pool (initially None)
REDIS_POOL = None
# ---
async def get_redis_client():
"""
This function initializes the Redis connection pool on the first call
and retrieves/releases connections for dependency injection.
"""
global REDIS_POOL
if REDIS_POOL is None:
# Configure connection details and pool size as needed
REDIS_POOL = BlockingConnectionPool(timeout=5).from_url(
f"redis://{env.REDIS_USERNAME}:{env.REDIS_PASSWORD}@{env.REDIS_HOST}:{env.REDIS_PORT}/{env.REDIS_DB}")
connection = REDIS_POOL.get_connection(command_name="")
client = Redis(connection_pool=REDIS_POOL)
try:
yield client
finally:
REDIS_POOL.release(connection)
# Export the dependency function for use in API endpoints
redis = Depends(get_redis_client)
logger.debug("Initialized Redis connection pool")
|