Spaces:
Paused

tupload07 / biquge-api /app /cache.py
xiaodu1233
ok
6d2d8b6
Raw History Blame Contribute Delete
1.38 kB
"""线程安全的内存 TTL 缓存。"""
from __future__ import annotations
import threading
import time
from typing import Any
class TTLCache:
"""简单的键值缓存,过期后自动失效;线程安全。"""
def __init__(self, ttl: int = 60, maxsize: int = 512):
self.ttl = ttl
self.maxsize = maxsize
self._store: dict[str, tuple[float, Any]] = {}
self._lock = threading.Lock()
def get(self, key: str) -> Any | None:
with self._lock:
item = self._store.get(key)
if item is None:
return None
expires_at, value = item
if self.ttl > 0 and time.monotonic() - expires_at > self.ttl:
self._store.pop(key, None)
return None
return value
def set(self, key: str, value: Any) -> None:
if self.ttl <= 0:
return
with self._lock:
if len(self._store) >= self.maxsize:
# 淘汰最早过期的一半,避免缓存无限增长
for old_key in sorted(self._store, key=lambda k: self._store[k][0])[
: self.maxsize // 2
]:
self._store.pop(old_key, None)
self._store[key] = (time.monotonic(), value)
def clear(self) -> None:
with self._lock:
self._store.clear()