我想使用FastAPI-Cache2实现Redis缓存,并且我已经基于文档实现了缓存:
async def init_cache():
try:
redis = aioredis.from_url( # type: ignore
appConfig.REDIS_ENDPOINT,
encoding='utf-8',
decode_responses=False,
)
FastAPICache.init(RedisBackend(redis), prefix='igw-cache')
logging.info('Cache initialized successfully.')
except Exception as e:
logging.error(f'Error initializing cache: {e}')
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
await init_cache()
yield
最后:
app = FastAPI(lifespan=lifespan, docs_url=docs_url)
@router.get("/test-cache")
@cache(expire=60)
async def index(request: Request, response: Response):
logging.info('The endpoint executed...')
return dict(hello="world")
每当我调用端点时,我都会在 Redis 中看到唯一的键和值,但也会打印
The endpoint executed...
日志。如何确保它按照我预期的方式工作,60 秒内看不到日志?
嗯,我实现了同样的方法,但我没有遇到你的问题,我的配置是:
安装:
pip install fastapi-cache2
初始化:
@asynccontextmanager
async def lifespan(app: FastAPI):
# connect redis
redis = Redis(host='localhost', port=6379)
app.state.redis = redis
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
yield
app.state.redis.close()
app = FastAPI(lifespan=lifespan)
我的路由器是:
@app.get('/test-cache')
@cache(expire=60)
async def test_cache():
print('the router has executed')
time.sleep(2)
return dict(hello="world")