AI掘金头条新闻系统 (Toutiao News)-缓存相关推荐新闻

1. cache/news_cache.py

python 复制代码
RELATED_NEWS_PREFIX = "news:related:"

# 写入缓存-相关新闻 key = news:related:新闻id:分类id + 相关新闻列表 + 过期时间
async def cache_related_news(news_id: int, category_id: int, related_list: List[Dict[str, Any]], expire: int = 1800) -> bool:
    key = f"{RELATED_NEWS_PREFIX}{news_id}:{category_id}"
    return await set_cache(key, related_list, expire)


# 读取缓存-相关新闻 key = news:related:新闻id:分类id
async def get_cached_related_news(news_id: int, category_id: int) -> Optional[List[Dict[str, Any]]]:
    key = f"{RELATED_NEWS_PREFIX}{news_id}:{category_id}"
    return await get_json_cache(key)

2. 改造crud/news.py

python 复制代码
# 获取相关推荐新闻
async def get_related_news(db: AsyncSession, news_id: int, category_id: int, limit: int = 5):
    # 先尝试从缓存获取相关新闻
    cached_related = await get_cached_related_news(news_id, category_id)
    if cached_related:
        return cached_related

    # 查询数据库
    stmt = (
        select(News)
        .where(
            News.id != news_id,
            News.category_id == category_id
        )
        .order_by(
            News.views.desc(),
            News.publish_time.desc()
        )
        .limit(limit)
    )

    result = await db.execute(stmt)
    related_news = result.scalars().all()

    related_list = [
        {
            "id": item.id,
            "title": item.title,
            "content": item.content,
            "image": item.image,
            "author": item.author,
            "publishTime": item.publish_time,
            "categoryId": item.category_id,
            "views": item.views
        }
        for item in related_news
    ]

    # 写入缓存
    if related_list:
        await cache_related_news(news_id, category_id, related_list)

    return related_list
相关推荐
犀利豆20 分钟前
Claude code tools 研究系列-开篇(AskUserQuestion)
后端
min(a,b)1 小时前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
yangshicong3 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华3 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb72883 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
暖和_白开水3 小时前
数据分析agent(十三_3):docker mysql容器镜像服务的异常错误
mysql·docker·容器
颜酱3 小时前
06 | 把 meta_config 同步进 MySQL(生成阶段)
前端·人工智能·后端
IT_陈寒4 小时前
SpringBoot自动配置坑了我一周,原来问题这么蠢!
前端·人工智能·后端
chenment5 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
REDcker5 小时前
Cesium三维WebGIS入门详解
前端·gis·web·cesium·webgis