27 lines
857 B
Python
27 lines
857 B
Python
import config
|
|
import redis
|
|
from models import QueryResponse, ICPRecord
|
|
from typing import List, Optional
|
|
|
|
# test redis
|
|
r = redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT, password=config.REDIS_PASSWORD, db=config.REDIS_DB)
|
|
|
|
# if ping failed, raise exception
|
|
if not r.ping():
|
|
raise Exception("Redis ping failed")
|
|
|
|
|
|
MAX_EXPIRE_TIME = 6 * 60 * 60
|
|
|
|
def save_to_cache(domain: str, data: List[ICPRecord]):
|
|
# 将data转换为json字符串
|
|
# 直接转换
|
|
data_json = QueryResponse(cached=False, count=len(data), data=data).model_dump_json()
|
|
r.set(f"{config.REDIS_PREFIX}:{domain}", data_json, ex=MAX_EXPIRE_TIME)
|
|
|
|
def load_from_cache(domain: str) -> Optional[List[ICPRecord]]:
|
|
data_json = r.get(f"{config.REDIS_PREFIX}:{domain}")
|
|
if data_json:
|
|
return QueryResponse.model_validate_json(data_json).data
|
|
return None
|