36 lines
1.0 KiB
Python
36 lines
1.0 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from redis.asyncio import Redis
|
|
from redis.exceptions import RedisError
|
|
|
|
|
|
class RedisHotCache:
|
|
"""Best-effort accelerator; callers must always retain a PostgreSQL fallback."""
|
|
|
|
def __init__(self, client: Redis | None) -> None:
|
|
self.client = client
|
|
|
|
async def get(self, key: str) -> dict[str, Any] | None:
|
|
if not self.client:
|
|
return None
|
|
try:
|
|
value = await self.client.get(f"han:safety:{key}")
|
|
return json.loads(value) if value else None
|
|
except (RedisError, ValueError, TypeError):
|
|
return None
|
|
|
|
async def put(self, key: str, value: dict[str, Any], ttl: int) -> None:
|
|
if not self.client:
|
|
return
|
|
try:
|
|
await self.client.set(
|
|
f"han:safety:{key}",
|
|
json.dumps(value, separators=(",", ":"), sort_keys=True),
|
|
ex=ttl,
|
|
)
|
|
except RedisError:
|
|
return
|