当前位置:网站首页>Using redis database as cache in Django
Using redis database as cache in Django
2022-06-26 01:14:00 【Oh, Yu è】
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
边栏推荐
猜你喜欢
![Chapter VI exercises (678) [microcomputer principles] [exercises]](/img/20/b02bccebfb245d4710f6f48dd0f5e4.png)
Chapter VI exercises (678) [microcomputer principles] [exercises]

Computer network knowledge summary (interview)

The maze of God's perspective in robot vision

Duck feeding data instant collection solution resources

计算机网络知识总结(面试)

Blob

随便画画的

填鸭数据即时收集解决方案资源

Summary of push-pull output and open drain output of STM32 and failure of analog IIC driving mlx90615

Digital circuit - adder
随机推荐
Modelsim simulation FFT core cannot be simulated solution (qsys)
Preorder and middle order traversal of forest
Solution to MySQL error code 2003
vite打包构建时 @charset utf-8警告问题处理;
Essence and thoughts of 30 lectures on product thinking
Containerd client comparison
Error 65:access violation at 0x58024400: no 'read' permission
FPGA notes -- implementation of FPGA floating point operation
马斯克 VS 乔布斯,谁是21世纪最伟大的创业家
About EF page turning query database
Establish a j-link GDB cross debugging environment for Px4
[learn FPGA programming from scratch -44]: vision chapter - integrated circuit helps high-quality development in the digital era -1- main forms of integrated circuit chips
[从零开始学习FPGA编程-44]:视野篇 - 集成电路助力数字化时代高质量发展-1-集成电路芯片主要形态
随便画画的
Data analysis slicer, PivotTable and PivotChart (necessary in the workplace)
在线小工具分享(不定时更新,当前数量:2)
统一网关Gateway
Enlightenment Q & A
Idea configuration
Redis strings command