AI掘金头条新闻系统 (Toutiao News)-缓存新闻详情

1. cache/news_cache.py

python 复制代码
NEWS_DETAIL_PREFIX = "news:detail:"

# 读取缓存-新闻详情 key = news:detail:新闻id
async def get_cached_news_detail(news_id: int) -> Optional[Dict[str, Any]]:
    key = f"{NEWS_DETAIL_PREFIX}{news_id}"
    return await get_json_cache(key)


# 写入缓存-新闻详情 key = news:detail:新闻id + 新闻数据 + 过期时间
async def cache_news_detail(news_id: int, news_data: Dict[str, Any], expire: int = 300) -> bool:
    key = f"{NEWS_DETAIL_PREFIX}{news_id}"
    return await set_cache(key, news_data, expire)

2. 改造crud/news.py

python 复制代码
# 获取新闻详情
async def get_news_detail(
        db: AsyncSession,
        new_id : int
):
    # 先尝试从缓存获取新闻详情
    cached_detail = await get_cached_news_detail(new_id)
    if cached_detail:
        return News(**cached_detail)

    # 查询数据库
    stmt = select(News).where(News.id == new_id)
    result = await db.execute(stmt)
    news = result.scalar_one_or_none()

    # 写入缓存
    if news:
        news_data = jsonable_encoder(news)
        await cache_news_detail(new_id, news_data)

    return news
相关推荐
小满zs19 分钟前
Go语言第三章(五谷轮回)
后端·go
tkevinjd3 小时前
MiniCode 项目详解6:原项目控制系统的10个缺陷(已修复)
python·llm·agent
雨辰AI3 小时前
全集实战:企业级大模型服务化部署全栈指南|FastAPI 封装 + Nginx 负载均衡 + 高可用架构 从单机到生产一步到位
人工智能·ai·负载均衡·fastapi·ai编程
dNGUZ7UGj4 小时前
10分钟完成第一个Python小游戏
python·django
没有梦想的咸鱼185-1037-16634 小时前
AI-Python机器学习与深度学习技术:CNN/Transformer/扩散模型、SHAP可解释及Hermes智能体自动化
人工智能·python·深度学习·机器学习·chatgpt·cnn·transformer
霸道流氓气质4 小时前
SpringBoot中通用工具类库(Utils)封装与使用实践
spring boot·后端·python
Draina6 小时前
CBC填充预言攻击-CBC Padding Oracle Crypto Attack
python·安全·web安全·网络安全·密码学·安全性测试
Angel Q.7 小时前
特征提取 | DINO 到 DINOv3
图像处理·python
瞬间&永恒~7 小时前
【MySQL】4-6:在同一个主机上使用 systemd 运行多个 MySQL服务器
服务器·数据库·mysql