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
相关推荐
FYKJ_20103 分钟前
springboot刑事案件管理系统03047-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
Python图像识别1 小时前
18-【2027毕设】YOLO11烟雾检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·深度学习·yolo·毕业设计·毕设
FYKJ_20101 小时前
springboot助农产品销售商城05829-计算机课程设计、毕业设计
java·spring boot·python·mysql·spark·django
Yunovian1 小时前
AI时代,针对模型与应用,浅谈一下各编程语言
开发语言·c++·人工智能·python·ai·rust·ai编程
Kamille Bidan1 小时前
MySQL数据库引擎介绍
mysql
weixin_457760001 小时前
基于 YOLO11m-Pose 的动物姿态估计系统:从 Animal-Pose 标注到 Python 桌面部署
人工智能·python·深度学习
Ticnix2 小时前
RAG 烂大街?烂大街的只是那条流水线——真正的分水岭在这五处
后端·python·agent
Wx-bishekaifayuan2 小时前
springboot社区扶贫救助管理系统13300-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
DolphinDB2 小时前
数据库自带 Agent:10 分钟搭起 DolphinX-Web 数据入库与分析框架
后端·架构
弈栈录3 小时前
基于 Spring Boot 构建生产级 AI 应用平台
后端·面试·架构