insightfy-bloom-ms-ems / REDIS_CONNECTION_UPDATE.md
PupaClic
redis
537cb9b

Redis Connection Update - EMS

Summary

Updated EMS Redis and MongoDB connection handling to use centralized insightfy_utils connectors instead of direct motor/redis imports, making it consistent with other microservices.

Changes Made

1. app/nosql.py - Refactored to Use Centralized Connectors

Before:

  • Used motor.motor_asyncio.AsyncIOMotorClient directly
  • Used redis.asyncio.Redis directly
  • More verbose implementation

After:

  • ✅ Uses create_mongo_connection() from insightfy_utils.db.mongo_connector
  • ✅ Uses create_redis_connection() from insightfy_utils.db.redis_connector
  • ✅ Cleaner, more maintainable code
  • ✅ Consistent with ANS/TMS/RMS/MPMS pattern
  • ✅ Maintains all health checks and lifecycle functions

2. app/app.py - Migrated to Modern Lifespan Pattern

Before:

@app.on_event("startup")
async def startup():
    await connect_to_database()

@app.on_event("shutdown")
async def shutdown():
    await disconnect_from_database()

After:

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager."""
    # Startup
    await connect_to_database()  # SQL
    await connect_stores()       # MongoDB + Redis
    
    yield
    
    # Shutdown
    await disconnect_from_database()  # SQL
    await disconnect_stores()         # MongoDB + Redis

app.router.lifespan_context = lifespan

Benefits

  1. Consistency: Now matches the pattern used across all microservices
  2. Modern FastAPI: Uses @asynccontextmanager instead of deprecated @app.on_event()
  3. Maintainability: Uses centralized connectors from insightfy_utils
  4. Reliability: Proper lifecycle management with health checks for all stores
  5. Less Code: Removed verbose motor/redis imports

Configuration

No changes to configuration - still supports both formats:

Option 1: Single URL (Recommended)

CACHE_URL=redis://localhost:6379/0

Option 2: Separate Components (Backward Compatible)

CACHE_URI=localhost:6379
CACHE_K=your_password  # optional
CACHE_DB=0  # optional

Migration Notes

  • No breaking changes - all existing configurations work as before
  • All existing imports remain unchanged
  • NoSQL stores now properly managed in application lifecycle
  • Migrated from deprecated @app.on_event() to modern lifespan pattern

Testing

Verify the changes:

cd insightfy-bloom-ms-ems
python -m uvicorn app.app:app --reload

# Check logs for:
# - "Starting EMS application"
# - "MongoDB client initialized"
# - "Redis client initialized"
# - "Store connectivity OK (Mongo & Redis)"
# - "Database connections established"

Related Files

  • app/nosql.py - Updated to use centralized connectors
  • app/app.py - Migrated to lifespan pattern
  • ℹ️ settings.py - No changes needed
  • ℹ️ All other files - No changes needed