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
相关推荐
执子手 吹散苍茫茫烟波2 小时前
RC 隔离级别下 MySQL InnoDB 死锁典型案例
数据库·mysql
tryCbest3 小时前
Python 文件操作
服务器·python
涛声依旧-底层原理研究所3 小时前
Agent 长任务可靠性设计:实现暂停、恢复、续跑与崩溃重启的完整方案
人工智能·python·系统架构
AC赳赳老秦3 小时前
防火墙规则批量配置实战:OpenClaw 自动生成模板、批量下发与合规性校验全解析
java·开发语言·人工智能·python·github·php·openclaw
小小编程路3 小时前
如何优化while循环的性能?
python
卷无止境4 小时前
C++ 存储类说明符(Storage Class Specifier)大横评
c++·后端
用户019027581614 小时前
量化数据的 batch 接口有多好用?从 1 只到 500 只,批量拉数据的正确姿势
后端
rruining4 小时前
Java设计模式——结构型
后端
卷无止境4 小时前
C++ 编程的一大坑:非常量全局变量是"万恶之源"
c++·后端
lzqrzpt4 小时前
LED驱动电源选型标准与工程应用技术要点解析
python·单片机·嵌入式硬件·物联网