此前,我也有这个问题。最后,我使用Redis。
而在werkeug
中,有一个缓存库,这使得Redis易于使用。
from werkzeug.contrib.cache import RedisCache
了解更多信息,请参阅doc
顺便说一句,如果你的应用程序在单一的进程中运行(多线程也行),你可以使用下面的代码。
class CachedItem:
def __init__(self, item, duration):
self.item = item
self.duration = duration
self.time_stamp = time.time()
def __repr__(self):
return '<CachedItem {%s} expires at: %s>' % (self.item, time.time() + self.duration)
class CachedDict(dict):
def __init__(self, *args, **kwargs):
super(CachedDict, self).__init__(*args, **kwargs)
self.lock = threading.Lock()
def get_cache(self, key, default=None, duration=300):
with self.lock:
self._clean()
if key in self:
return self[key].item
else:
self[key] = CachedItem(default, duration)
return self[key].item
def set_cache(self, key, value, duration=300):
with self.lock:
self[key] = CachedItem(value, duration)
def _clean(self):
for key in list(self.keys()): # [self.keys()] error, we get dict_keys type
if self[key].time_stamp + self[key].duration <= time.time():
self.pop(key)
瓶颈高速缓存缓存对请求的响应。 lru_cache缓存函数的返回值,CacheTools为您提供了不同的缓存策略,并且您对它们的处理由您决定。我不知道弹簧引导是做什么的,但它取决于你的需求,你想要缓存什么位置和什么,并且没有单一的解决方案。 – syntonym
嗨,我基本上想缓存数据而不是请求,因为我的请求几乎都是唯一的。 – xmen