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

  

posted @ 2023-07-12 17:14  不识少年愁  阅读(103)  评论(0编辑  收藏  举报