Skip to content

Commit

Permalink
Merge pull request #349 from LACMTA:2023-api-optimization
Browse files Browse the repository at this point in the history
hotfix: Call initialize_redis at fastapi startup
  • Loading branch information
albertkun authored Nov 10, 2023
2 parents 0d6a5a1 + 209c964 commit 02b8222
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions fastapi/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,18 @@

def initialize_redis():
global redis
logging.info(f"Connecting to Redis at {Config.REDIS_URL}")
for i in range(5): # Retry up to 5 times
try:
redis = aioredis.from_url(Config.REDIS_URL, socket_connect_timeout=5)
break # If the connection is successful, break out of the loop
except aioredis.exceptions.ConnectionError:
except aioredis.exceptions.ConnectionError as e:
logging.error(f"Failed to connect to Redis: {e}")
if i < 4: # If this was not the last attempt, wait a bit before retrying
time.sleep(5) # Wait for 5 seconds
else: # If this was the last attempt, re-raise the exception
raise

async def get_data(db: Session, key: str, fetch_func):
# Get data from Redis
data = await redis.get(key)
Expand Down Expand Up @@ -715,8 +717,9 @@ async def get_all_routes():

@app.on_event("startup")
async def startup_event():
initialize_redis()
app.state.redis = await aioredis.from_url(Config.REDIS_URL, socket_connect_timeout=5)
await app.state.redis.flushdb() # Add this line to flush the Redis database
# await app.state.redis.flushdb() # Add this line to flush the Redis database
uvicorn_access_logger = logging.getLogger("uvicorn.access")
uvicorn_error_logger = logging.getLogger("uvicorn.error")
logger = logging.getLogger("uvicorn.app")
Expand All @@ -741,10 +744,6 @@ async def startup_event():
uvicorn_error_logger.addFilter(LogFilter())
logger.addFilter(LogFilter())

@app.on_event("shutdown")
async def shutdown_event():
app.state.redis.close()
await app.state.redis.wait_closed()

app.add_middleware(
CORSMiddleware,
Expand Down

0 comments on commit 02b8222

Please sign in to comment.