django 缓存系统
https://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api
http://www.ziqiangxuetang.com/django/django-cache.html
可以缓存能被pickle的对象
安装
pip install hiredis django-redis-cache
setting中配置
#KEY_PREFIX 设置缓存键值的前缀
CACHES = { ‘mysql‘: { ‘BACKEND‘: ‘django.core.cache.backends.db.DatabaseCache‘, ‘LOCATION‘: ‘cache‘, }, ‘dummy‘: { ‘BACKEND‘: ‘django.core.cache.backends.dummy.DummyCache‘ }, ‘redis‘: { ‘BACKEND‘: ‘redis_cache.RedisCache‘, ‘LOCATION‘: [ ‘127.0.0.1:6379‘, # ‘<host>:<port>‘, # ‘<host>:<port>‘, ], ‘OPTIONS‘: { ‘DB‘: 1, # ‘PASSWORD‘: ‘yadayada‘, ‘PARSER_CLASS‘: ‘redis.connection.HiredisParser‘, ‘CONNECTION_POOL_CLASS‘: ‘redis.BlockingConnectionPool‘, ‘CONNECTION_POOL_CLASS_KWARGS‘: { ‘max_connections‘: 50, ‘timeout‘: 20, }, ‘PICKLE_VERSION‘: -1, # ‘MASTER_CACHE‘: ‘<master host>:<master port>‘, }, }, } CACHES[‘default‘]=CACHES[‘redis‘] #必须有一个default配置
#使用cache
from django.core.cache import cachescache=caches[‘redis‘]#使用redis做为缓存, >>> cache.set(‘my_key‘, ‘hello, world!‘, 30) 设置一个key并且30秒后过期 >>> cache.get(‘my_key‘) >>> cache.get_many([‘a‘, ‘b‘, ‘c‘]) >>> cache.set_many({‘a‘: 1, ‘b‘: 2, ‘c‘: 3}) >>> cache.delete_many([‘a‘, ‘b‘, ‘c‘]) >>> cache.clear()#情况当前所有缓存 >>> cache.incr(‘num‘)#使当前值+1 >>> cache.incr(‘num‘, 10) #当前值+10 >>> cache.decr(‘num‘)#值-1 >>> cache.decr(‘num‘, 5)#值-5
cache version 缓存版本
cache.set(‘my_key‘, ‘hello world!‘)#默认为版本一 "SETEX" ":1:my_key" "300" "\x80\x02U\rhello python!q\x01." cache.set(‘my_key‘, ‘hello world!‘, version=2) redis 命令 "SETEX" ":2:my_key" "300" "\x80\x02U\x03666q\x01." cache.get(‘my_key‘,version=2)
时间: 2024-10-13 09:08:52