def register_redis(app: FastAPI) -> None: """ 把redis掛載到app物件上面 :param app: :return: """ @app.on_event('startup') async def startup_event(): """ 獲取連結 :return: """ async def redis_pool(): redis = await from_url( url=settings.REDIS_URL, port=settings.REDIS_PORT, password=settings.REDIS_PASSWORD, db=settings.REDIS_DB, encoding="utf-8", decode_responses=True ) return redis app.state.redis = await redis_pool() @app.on_event('shutdown') async def shutdown_event(): """ 關閉 :return: """ await app.state.redis.close()