FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀

2. 核心原理:收银员与小本本

PostgreSQL 想象成超市的总仓库 ,每次查询都得跑大老远去取货。Redis 就是收银员随身带的小本本,记下最常卖的商品(热点数据)。下次顾客要,直接从小本本查,秒级响应。

Elasticsearch 呢?它像个档案管理员,把所有日志分门别类建索引,你可以用关键词秒搜到任何请求的细节,再也不用登录服务器翻文件了。

3. 开干!FastAPI + Redis + ES 集成

假设你已经有个FastAPI项目,连了PostgreSQL。咱们一步步加料。

🔧 3.1 安装依赖

复制代码
pip install redis elasticsearch[async] fastapi-cache2[redis]

这里用了fastapi-cache库,封装了缓存装饰器,省得自己写重复代码。当然你也可以直接用aioredis,看个人喜好。

📝 3.2 Redis缓存装饰器实战

创建一个缓存工具模块:

复制代码
# app/cache.py
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
import redis.asyncio as redis

async def init_cache(redis_url: str = "redis://localhost:6379"):
    redis_client = redis.from_url(redis_url, encoding="utf-8", decode_responses=True)
    FastAPICache.init(RedisBackend(redis_client), prefix="fastapi-cache")

然后在启动事件中调用:

复制代码
# main.py
from app.cache import init_cache

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

重点来了 :在需要缓存的接口上加@cache()装饰器:

复制代码
@app.get("/items/{item_id}")
@cache(expire=60)  # 缓存60秒
async def get_item(item_id: int, db: Session = Depends(get_db)):
    # 这里是数据库查询
    item = db.query(Item).filter(Item.id == item_id).first()
    return item

就这么简单!同样的请求60秒内直接走Redis,数据库连看都不看一眼。

⚠️ 这里我踩过一个坑: 如果接口参数里有db session这种不可哈希的对象,fastapi-cache会报错。解决办法是把依赖项移到装饰器外面,或者用cache(..., key_builder=...)自定义键。

📜 3.3 Elasticsearch日志中间件

日志不能只打控制台,要统一送ES。我们写一个中间件,记录每次请求的方法、路径、状态码、耗时等。

复制代码
# app/log_middleware.py
from elasticsearch import AsyncElasticsearch
import time
import json

es = AsyncElasticsearch(["http://localhost:9200"])

@app.middleware("http")
async def log_to_es(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start

    log_data = {
        "method": request.method,
        "url": str(request.url),
        "status_code": response.status_code,
        "duration": round(duration, 4),
        "client_ip": request.client.host,
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    }

    # 异步发送日志,别阻塞请求
    await es.index(index="fastapi-logs", document=log_data)
    return response

注意: 生产环境千万别每个请求都同步发ES,得用批量发送+缓冲 ,或者用background tasks。上面只是demo,实际要优化。

4. 那些年我踩过的坑(必看)

集成完了?别急,下面这几个坑我挨个帮你排雷。

🔥 坑1:缓存穿透 --- 查询一个不存在的id,每次都会穿透到数据库。解决方案:缓存空值或布隆过滤器。

🔥 坑2:ES索引爆炸 --- 如果不管理索引生命周期,日志会把磁盘撑爆。一定要用ILM(索引生命周期管理)或定时删除旧索引。

🔥 坑3:异步Redis连接未关闭 --- 服务停止时忘记关闭Redis连接,导致警告。在shutdown事件里加await FastAPICache.clear()redis_client.close()

🔥 坑4:ES连接失败导致请求阻塞 --- 日志中间件里要加try-except,否则ES挂掉整个API也挂了。

是不是以为这样就完了?No no no,还有进阶操作:

✅ 用缓存预热,在启动时加载热门商品到Redis。

✅ 给ES日志加上APM trace ID,配合链路追踪。

✅ 把缓存装饰器封装成统一@custom_cache,自动处理异常和降级。

相关推荐
打工仔折腾 AI11 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
风哥2号13 小时前
数据库教程FGMT51‑PostgreSQL实例管理与参数文件
数据库·postgresql
wdfk_prog15 小时前
ROS教程10:从 gtest 到 rostest——Unit Test、Node 集成测试、rosbag 与 rqt 验证闭环
运维·缓存·docker·容器·ros
lusklusklusk15 小时前
Oracle索引组织表,SQLServer聚集索引,Mysql Innodb表的数据行不是在磁盘上像排队一样严格连续地存放
mysql·postgresql·oracle·sqlserver
redfred19 小时前
Outline 部署教程:4 万 Star 自托管知识库,免费替代 Notion(Windows 源码部署完整指南)
postgresql·开源软件·notion
程序猿乐锅21 小时前
【黑马点评 | 第四篇】Redis缓存雪崩
java·数据库·spring boot·redis·缓存
jnrjian21 小时前
公司有CA服务器生成cert key csr
postgresql·redhat
jnrjian1 天前
EDB CA cert key
postgresql
西安栈上月明软件科技1 天前
从 Linux 0.01 到 AI 开源:星图邻的开源实践
人工智能·自然语言处理·架构·开源·fastapi
HanhahnaH1 天前
Redis单线程和Tair多线程架构设计对比
分布式·缓存