# --- 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")