mirror of
https://github.com/stardrophere/InsightRadar.git
synced 2026-06-06 00:00:05 +08:00
缓存优化
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
# app/api/endpoints/events.py
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from typing import List
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -26,6 +27,10 @@ router = APIRouter()
|
||||
# 排名轨迹最多返回多少个点,避免长时间跨度下数据过大
|
||||
MAX_RANKING_POINTS = 30
|
||||
|
||||
# --- 轻量级接口缓存配置 ---
|
||||
_UNIFIED_EVENTS_CACHE: Dict[str, Tuple[float, PaginatedUnifiedEventResponse]] = {}
|
||||
CACHE_TTL_SECONDS = 60
|
||||
# ---------------------------
|
||||
|
||||
@router.get("/unified", response_model=PaginatedUnifiedEventResponse)
|
||||
def list_unified_events(
|
||||
@@ -37,6 +42,17 @@ def list_unified_events(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""分页返回统一事件,附带各平台热搜、排名轨迹和标签。"""
|
||||
|
||||
# --- 1. 尝试从缓存读取 ---
|
||||
cache_key = f"{min_hot}:{hours}:{sort_by}:{skip}:{limit}"
|
||||
current_time = time.time()
|
||||
|
||||
if cache_key in _UNIFIED_EVENTS_CACHE:
|
||||
expire_time, cached_data = _UNIFIED_EVENTS_CACHE[cache_key]
|
||||
if current_time < expire_time:
|
||||
return cached_data
|
||||
# -----------------------
|
||||
|
||||
time_limit = utcnow() - timedelta(hours=hours)
|
||||
|
||||
# 先查总数,用于前端判断是否还有更多
|
||||
@@ -149,7 +165,17 @@ def list_unified_events(
|
||||
)
|
||||
|
||||
has_more = (skip + limit) < total
|
||||
return PaginatedUnifiedEventResponse(total=total, has_more=has_more, data=results)
|
||||
response = PaginatedUnifiedEventResponse(total=total, has_more=has_more, data=results)
|
||||
|
||||
# --- 2. 写入缓存 ---
|
||||
if len(_UNIFIED_EVENTS_CACHE) > 1000:
|
||||
# 防止内存无限增长
|
||||
_UNIFIED_EVENTS_CACHE.clear()
|
||||
|
||||
_UNIFIED_EVENTS_CACHE[cache_key] = (current_time + CACHE_TTL_SECONDS, response)
|
||||
# ------------------
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/unified/{event_id}", response_model=UnifiedEventResponse)
|
||||
|
||||
Reference in New Issue
Block a user