"""章节数据持久化缓存(SQLite),防止频繁抓取同一章节。""" from __future__ import annotations import json import sqlite3 import threading import time import os from pathlib import Path DEFAULT_DB_PATH = Path( os.getenv( "CHAPTER_CACHE_DB_PATH", str(Path(__file__).resolve().parent.parent / "data" / "chapter_cache.db"), ) ) DEFAULT_TTL = 7 * 24 * 3600 # 默认 7 天 class ChapterCache: def __init__(self, path: str | Path = DEFAULT_DB_PATH, ttl: int = DEFAULT_TTL) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) self.ttl = ttl self._conn = sqlite3.connect(str(path), check_same_thread=False) self._lock = threading.Lock() with self._lock: self._conn.execute( """ CREATE TABLE IF NOT EXISTS chapter_cache ( key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at REAL NOT NULL ) """ ) self._conn.execute( "CREATE INDEX IF NOT EXISTS idx_chapter_cache_expires " "ON chapter_cache(expires_at)" ) self._conn.commit() def get(self, key: str) -> dict | None: with self._lock: row = self._conn.execute( "SELECT value, expires_at FROM chapter_cache WHERE key = ?", (key,) ).fetchone() if row is None: return None value, expires_at = row if expires_at <= time.time(): self._conn.execute("DELETE FROM chapter_cache WHERE key = ?", (key,)) self._conn.commit() return None return json.loads(value) def set(self, key: str, value: dict, ttl: int | None = None) -> None: expires = time.time() + (ttl if ttl is not None else self.ttl) with self._lock: self._conn.execute( """ INSERT INTO chapter_cache (key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at """, (key, json.dumps(value, ensure_ascii=False), expires), ) # 顺带清理过期数据 self._conn.execute( "DELETE FROM chapter_cache WHERE expires_at <= ?", (time.time(),) ) self._conn.commit()