程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Using redis database as cache in Django

編輯:Python

What is the Redis?

redis It's a key-value The storage system .
First we need to understand redis What can be done ?
redis Not just caching , You can also do : Ranking List 、 Calculator 、 Speed governor 、 Friend relationship 、 Simple message queuing 、session The server


In daily project development , When our database gets bigger , Searching the database in the background will become very slow , At this time, we need cache to help us improve the efficiency of the browser

There is a basic trade-off between dynamic websites —— They are dynamic . One page per user request ,web The server needs to provide a variety of calculations —— From database query to template rendering to business logic —— Finally, create a page to present to the user . In terms of processing overhead , This is much more expensive than a standard read file system service arrangement .

We can cache some calculation results after a lot of trouble

Django With a powerful caching system , You can save dynamic pages , This way, you don't have to calculate every time you request a page .

Memcached

Memcached Is a fully memory based cache server , yes Django The fastest native support 、 The most efficient cache type

  • The cache can also be stored in the database
CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
'TIMEOUT': '60' * 5 # Cache expiration time 
}
}

We are setting Enter these lines of code in the configuration file ,location Is our cache database name
Using this my_cache_table Before caching the database , You must first create a cache table

python manage.py createcachetable

stay terminal The data above
Then you can write a code like this to verify

def news(request):
result = cache.get('news')
print(result)
# If cache There's cached data in , Then return directly 
if result:
return HttpResponse(result)
else:
news_list = []
for i in range(10):
news_list.append(' Hello Hello %d' % i)
sleep(5)
data = {

'news_list': news_list
}
response = render(request,'news.html',context=data)
# If cache No cached data in , Save data 
cache.set('news',response.content,timeout=60)
return response

We put cache Name it news, When we enter this and execute this method , First judge result Whether there is , If it exists, it means cache There is , If it doesn't exist , Just store the data in news.html in , Then put the page content Set to cache
If we have an efficient database , We can do that , But in general , Ordinary databases can not effectively deal with the problems such as server crashes that occur only in real situations , If our server suddenly crashes , Then these caches must be gone
So we need an efficient cache database to improve server performance

Redis Use :

Actually redis It is similar to the common database in use , After all, they are all databases , But in use redis We still need to download redis
https://www.cnblogs.com/xing-nb/p/12146449.html

This address perfectly describes how to install and use redis, And provides the network disk method to download redis( I am here github It took a long time to download …)
After installation and startup , Start configuration

CACHES = {

'default': {

'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379', # The cache location 
'OPTION': {

'CLIENT_CLASS': 'django_redis.client.DefaultClient', # Client class 
}
}
}

Remember to start redis service , After configuration , The test code is the same as above , No need to change


Use the dual database caching mechanism :

We can also use the multi cache mechanism to continue to improve the efficiency :
First, in the settings.py Add the following code to the page :

CACHES = {

'default': {

'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'cache_table', # The cache location 
'TIMEOUT': 60
},
'redis_backend': {

'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379', # The cache location 
'OPTION': {

'CLIENT_CLASS': 'django_redis.client.DefaultClient', # Client class 
}
}
}

first default Is a normal database cache , the second redis_backends yes redis Database cache

#@cache_page(60, cache='redis_backend')
def renews(request):
cache = caches['redis_backend']
result = cache.get('renew')
if result:
return HttpResponse(result)
renews_list = []
for i in range(10):
renews_list.append('halouhalou%d' % i)
sleep(5)
data = {

'renews_list': renews_list
}
response = render(request, 'renew.html', context=data)
cache.set('renew', response.content, timeout=60)
return response

This code means that you can use decorators , You can also use cache = caches['redis_backend'] The way


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved