Django缓存系统实现过程解析缓存系统实现过程解析
在动态网站中,用户每次请求一个页面,服务器都会执行以下操作:查询数据库,渲染模板,执行业务逻辑,最后生成用户可
查看的页面。
这会消耗大量的资源,当访问用户量非常大时,就要考虑这个问题了。
缓存就是为了防止重复计算,把那些消耗了大量资源的结果保存起来,下次访问时就不用再次计算了。缓存的逻辑:
given a URL, try finding that page in the cache
if the page is in the cache:
return the cached page
else:
generate the page
save the generated page in the cache (for next time)
return the generated page
Django提供了不同粒度的缓存:你可以缓存某个页面,也可以只缓存很难计算、很消耗资源的某个部分,或者直接缓存整个
网站。
Django也可以和一些”下游”缓存一起协作,例如Squid和基于浏览器的缓存,这些类型的缓存你不直接控制,但是你可以提供
给他们站点哪部分应该被缓存和怎样被缓存(通过HTTP headers)。
设置缓存设置缓存
在settings中的CACHES中设置缓存,下面是几个可用的缓存选项:
Memcached
Django目前原生支持的最快最有效的缓存系统。要使用Memcached,需要下载Memcached支持库,一般是python-
memcached或者pylibmc。
然后设置BACKEND为django.core.cache.backends.memcached.MemcachedCache(使用python-memcached时)或者
django.core.cache.backends.memcached.PyLibMCCache(使用pylibmc时)。
设置LOCATION为ip:port或者unix:path。例如:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
或者
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'unix:/tmp/memcached.sock',
}
}
当使用pylibmc时,去掉unix:/前缀:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '/tmp/memcached.sock',
}
}
还可以在多台机器上运行Memcached进程,程序将会把这组机器当作一个单独的缓存,而不需要在每台机器上复制缓存值:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'172.19.26.240:11211',
'172.19.26.242:11212',
'172.19.26.244:11213',