我有一个基于 django 的 http 服务器,我使用 django.core.cache.backends.memcached.MemcachedCache 作为客户端库来访问内存缓存。我想知道我们是否可以设置超时或其他设置(比如 500 毫秒),以便在 500 毫秒内无法访问缓存时,对 memcached 的调用返回 False。然后我们调用数据库。有这样的设置吗?
最佳答案
以前没有尝试过,但您可以使用线程并为缓存函数调用设置超时。例如,忽略此链接正文中提供的示例,但请查看 Jim Carroll 的评论:
http://code.activestate.com/recipes/534115-function-timeout/
适用于您可能使用的东西:
from threading import Timer
import thread, time, sys
def timeout():
thread.interrupt_main()
try:
Timer(0.5, timeout).start()
cache.get(stuff)
except:
print "Use a function to grab it from the database!"
我现在没有时间测试它,但我担心的是 Django 本身是否是线程化的,如果是,那么中断主线程是否是您真正想要做的?无论哪种方式,它都是一个潜在的起点。我确实在寻找允许这样做的配置选项,但一无所获。
关于python - 在内存缓存中获取/放入数据时指定超时(django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9998418/