一: 为什么要使用缓存服务器?
1. 提高服务器查询性能, 应为放在缓存服务器中的数据一般都是存储在内存当中的, 内存中的数据读写效率更高
2. 减少服务器端的压力, 提高服务器的查询性能
3. 减少数据库频繁查询的压力, 提升mysql的使用率
二: 操作
1. 配置django使用redis作为缓存服务器
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
2. 配置django使用redis作为session存储引擎
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
3. 在视图函数中
3.1>
# cache: django中的缓存
from django.core.cache import cache
先梳理逻辑:
首先, 既然你要用到缓存服务器, 所以在进行数据返回的时候, 就先到redis里面找到对应的数据, 如果找不到再去数据库里找, 然后将其返回, 同时也需要将此次浏览的地址以及数据存储到redis中, 方便下载查询!
注意: 一般只保存一些频繁访问的数据, 可以做个判断
例如:
def index(request):
# 以访问的url地址作为key,先从redis中读取数据,如果读取到直接返回数据
url = request.path
response_content = cache.get(url)
if response_content:
return HttpResponse(content=response_content)
else:
stus = Student.objects.all()
# 该访问地址没有存储过数据
response = render(request,'index.html',{'stus':stus})
# 以url地址作为key,response.content 作为值存储到redis缓存服务器中
cache.set(url,response.content)
return response
这里面有这么几个重要的参数
request.path: 当前页面的url(可直接使用)
cache.set: 写入(key, value)
cache.get: 读取
3.2>
当从后台获取到用户要请求数据的关键参数, 先在redis进行读取, 如果有
def search(reqeust):
if reqeust.method == 'POST':
ua = reqeust.POST.get('ua')
value = cache.get(ua)
if value:
# 使用redis作为session的存储引擎
reqeust.session['key'] = '123456'
data = value
else:
# 取出需要查询的数据,以ua作为key,取出的数据作为值,存储到redis中
data = {'username':'张三','age':22,'phone':110}
data = json.dumps(data)
session_value =reqeust.session['key']
print(session_value)
# key value
cache.set(ua,data)
response = render(reqeust,'result.html',{'datas':json.loads(data)})
return response