python实现ttl缓存
import time
import functools
import threading
def ttl_cache(func):
cache = {}
lock = threading.Lock()
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = args
for item in kwargs.items():
key += item
key = hash(key)
with lock:
if key in cache:
value, timestamp = cache[key]
if time.time() - timestamp < 600:
return value
result = func(*args, **kwargs)
cache[key] = (result, time.time())
return result
return wrapper

浙公网安备 33010602011771号