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
相关推荐
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 应用平台
后端·面试·架构