在Docker环境的Django项目中配置FastAPI-Cache遇Redis连接问题
问题解决指南
1. Redis连接失败的根源与修复
你碰到的第一个报错 redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. -2,核心原因是Redis服务没启动,或者你的应用无法定位到Redis实例。
解决步骤:
- 本地开发:直接执行
redis-server启动Redis服务;Windows环境需先完成Redis安装,再通过服务管理器启动。 - Docker环境:检查Redis容器是否在运行,且容器名称为
redis(你代码里用的redis://redis依赖Docker内部DNS解析容器名),如果容器名不符,修改连接URL里的主机名即可。 - 验证连接:用
redis-cli ping测试,返回PONG就说明服务正常。
2. requirements.txt安装redis-server失败的问题
redis-server不是Python包,PyPI上根本没有这个分发版本,所以你加在requirements.txt里肯定会报错。你需要安装的是Python操作Redis的客户端库,也就是redis包。
正确操作:
- 在requirements.txt中替换为:
redis>=5.0.0 - 执行
pip install -r requirements.txt完成安装。
3. 代码优化建议
看你的代码,补充几个关键点:
- 你混用了FastAPI和Django,要确保
async_safe()、get_logger_with_context这类自定义函数能正常导入和运行。 - 连接URL适配:本地开发时,把
redis://redis改成redis://localhost:6379;Docker环境下保留原配置即可。 - 缓存装饰器适配:把同步视图改成异步模式,更适配FastAPI Cache的Redis后端:
@router.get( "/companies/attributes", summary="Retrieve company attributes, including leadership attributes, perks and benefits, and industry", response_model=CompanyAttributesOut, status_code=200, ) @cache(expire=60, coder=JsonCoder) async def get_company_attributes() -> CompanyAttributesOut: """Retrieve the company attributes.""" with async_safe(): return CompanyAttributesOut.from_database_model()
内容的提问来源于stack exchange,提问作者Owen Percoco
相关产品推荐
相关产品推荐

