Django 缓存 使用 Redis Memcached 为网站提速
Redis
Redis是一种键值对类型的内存数据库,读写内存比读写硬盘快,我们在Django里面使用Redis非常方便,下面给出详细步骤
基于Ubuntu
1. 安装Redis和django-redis
sudo apt-get install redis-server
1
用 redis 做 Django的缓存系统的开源项目地址,有兴趣的看看:https://github.com/niwibe/django-redis
在这里我们把它装上,让Django和Redis手拉手交个朋友
pip install django-redis
1
2
2. 检查运行状态
ps -aux|grep redis
1
netstat -nlt|grep 6379
1
3. 修改seetings.py
#配置我是这么写的没问题
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': '127.0.0.1:6379',
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
},
}
1
2
3
4
5
6
7
8
9
10
#如果你的有问题,试试官方的写法 http://django-redis-chs.readthedocs.io/zh_CN/latest/#
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
1
2
3
4
5
6
7
8
9
10
4. 测试redis缓存
#进Django的shell里面
python manage.py shell
1
2
#从shell里面输入下面命令测试,不报错就正常,要是报错了要么没开启redis要么没装好,检查之前的步骤
from django.core.cache import cache
#写入key为key1,值为666的缓存,有效期30分钟
cache.set('key1', '666', 30*60)
cache.has_key('key1') #判断key为k是否存在
cache.get('key1') #获取key为k的缓存
1
2
3
4
5
6
5. 更新和读取缓存
之前在Views.py视图函数里面,收到form提交的更新只是写入数据库,现在增加个更新缓存
#写入缓存
key = 'QuestionCache'
from django.core.cache import cache
def ask_question(request):
question_category_name = request.POST['radio']
question_title = request.POST['question_title']
question_keywords = request.POST['question_keywords']
question_text = request.POST['question_content']
#没必要再设置这个字段了,models里面可以用auto_now自动获取当前时间的question_date = datetime.datetime.now()
question_author = request.user
joe = QuestionCategory.objects.get(category_name=question_category_name)
qqqq = Question(question_category=joe,question_title=question_title,question_keywords=question_keywords,question_text=question_text,question_author=question_author)
#写入数据库
qqqq.save()
#更新缓存
cache.set(key, list(Question.objects.all().order_by('-question_date')))
return redirect('pythonnav:blogindex_html')
# 读取缓存
def blogindex_html(request):
#获取问题所有分类
a = QuestionCategory.objects.all()
es = []
for e in a:
es.append(e.category_name)
# 展示所有的问题
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
limit = 10 # 每页显示的记录条数
#以前是直接从数据库查,每次都查数据多了要死人的,5555
#现在先判断下,如果redis内存里面有就从内存读,不从数据库里查了,耶,感觉萌萌哒
if cache.has_key(key):
question = cache.get(key)
else:
question = Question.objects.all().order_by('-question_date')
paginator = Paginator(question,limit)#实例化一个分页对象
page = request.GET.get('page') #获取到页码
try:
q = paginator.page(page) #获取某夜对应的记录
except PageNotAnInteger: #如果页码不是个整数
q = paginator.page(1)#取第一页的记录
except EmptyPage:#如果页码太大
q = paginator.page(paginator.num_pages)#取最后一页的记录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Memcached
使用前准备工作
1.ubuntu下先安装:
sudo apt-get install memcached
pip install python-memcached
1
2
2.启动memcached
memcached -d -m 64 -u www -l 127.0.0.1 -p 11211 -c 1024 -P /tmp/memcached.pid
1
-d选项是启动一个守护进程,
-m是分配给Memcache使用的内存数量,单位是MB,我这里设的是64MB,
-u是运行Memcache的用户,我这里是www,
-l是监听的服务器IP地址,如果有多个地址的话,用空格分隔
-p是设置Memcache监听的端口,我这里设置了11211,最好是1024以上的端口,
-c选项是最大运行的并发连接数,默认是1024
-P是设置保存Memcache的PID文件,我这里是保存在 /tmp/memcached.pid,方便查看PID
3.查看memcached:
启动成功后,查看进程状态:
ps -ef | grep memcached
1
查看11211端口状态:
netstat -ntl
1
memcached的配置文件路径:
/etc/sysconfig/memcached
1
4.测试memcache是否可以使用:
python manage.py shell 进入Django shell中
from django.core.cache import cache
cache.set('key1', 'test')
value = cache.get('key1')
print value
#得到结果test
1
2
3
4
5
1.Django中seetings里面的设置
使用IP端口与Django交互
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
也可以通过一个本地的Unix socket file/tmp/memcached.sock来交互
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'unix:/tmp/memcached.sock',
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
题外话:Memcached有一个非常好的特点就是可以让几个服务的缓存共享。 这就意味着你可以再几个物理机上运行Memcached服务,这些程序将会把这几个机器当做 同一个 缓存,从而不需要复制每个缓存的值在每个机器上。为了使用这个特性,把所有的服务地址放在LOCATION里面,用分号隔开或者当做一个list。
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'172.19.26.240:11211',
'172.19.26.242:11211',
]
}
}
1
2
3
4
5
6
7
8
9
2.Django中具体使用和Redis差不多
缓存数据
from django.core.cache import cache
def about(request):
if cache.get('key1'):
data = cache.get('key1')
else:
访问数据库,得到data
cache.set('data')
...
1
2
3
4
5
6
7
8
每次进来,先查看cache中是否存在,若存在,直接获得该值,若不存在,则访问数据库,
得到数据之后,将其写入到cache之后,以便后续之用。
缓存整个页面。
可以使用Django提供的cache_page装饰函数,例如缓存about页面:
from django.views.decorators.cache import cache_page
@cache_page(60*30)
def about(request):
...
1
2
3
只需在view函数前加上cache_page装饰函数便可以该页面,cache_page的参数是缓存时间
这里设的是60s*30,即30分钟。同时也可以指定使用的缓存,通过cache参数来指定,例如:
@cache_page(60*30, cache='file_cache')则指定使用settings文件中CACHES中的file_cache
来缓存,若不指定,默认用default的来缓存。
更多参考:
http://python.usyiyi.cn/translate/django_182/topics/cache.html
Django 缓存
Django缓存简介为什么要用缓存?我们知道,在Django中,请求到达视图后,视图会从数据库取数据放到模板中进行动态渲染,渲染后的结果就是用户看到的html页面。但是,如果每次请求都从数据库取数据并...
---------------------
作者:Peace & Love
来源:CSDN
原文:https://blog.csdn.net/u013205877/article/details/77397273?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!
Django 缓存 使用 Redis Memcached 为网站提速的更多相关文章
- Redis使用和部分源码剖析以及Django缓存和redis的关系
0.特点: a.持久化 b.单进程.单线程 c.5大数据类型 d.用于操作内存的软件. e.虽然是缓存数据库但是可以做持久化的工作 MySQL是一个软件,帮助开发者对一台机器的硬盘进行操作 ...
- 通过URLOS安装Redis缓存为wordpress网站提速
快!快!快!我们都知道网站的加载速度直接影响用户体验.据研究发现,网站页面在3秒内加载完毕对用户而言是最佳的浏览体验.如果超过这个时间,用户跳出网站的几率会非常大.所以对于站长来说,提高速度是他们追求 ...
- Django Cache缓存系统介绍及Memcached使用
在动态网站中,用户每次请求一个页面,服务器都会执行以下操作:查询数据库,渲染模板,执行业务逻辑,最后生成用户可查看的页面. 这会消耗大量的资源,当访问用户量非常大时,就要考虑这个问题了. 缓存就是为了 ...
- Django缓存机制以及使用redis缓存数据库
目录 Django 配置缓存机制 缓存系统工作原理 Django settings 中 默认cache 缓存配置 利用文件系统来缓存 使用Memcache来缓存: 使用Local-memory来缓存: ...
- 企业做数据缓存是使用Memcached还是选Redis?
企业是使用Memcached还是选Redis? 在构建一款现代且由数据库驱动的Web应用程序并希望使其拥有更为出色的性能表现时,这个问题总会时不时出现.并给每一位开发人员带来困扰.在考虑对应用程序的性 ...
- Django之使用redis缓存session,历史浏览记录,首页数据实现性能优化
Redis缓存session 配置Django缓存数据到redis中 # diango的缓存配置 CACHES = { "default": { "BACKEND&quo ...
- (转)高性能网站架构之缓存篇—Redis集群搭建
看过 高性能网站架构之缓存篇--Redis安装配置和高性能网站架构之缓存篇--Redis使用配置端口转发 这两篇文章的,相信你已经对redis有一定的了解,并能够安装上,进行简单的使用了,但是在咱们的 ...
- Python分布式爬虫打造搜索引擎完整版-基于Scrapy、Redis、elasticsearch和django打造一个完整的搜索引擎网站
Python分布式爬虫打造搜索引擎 基于Scrapy.Redis.elasticsearch和django打造一个完整的搜索引擎网站 https://github.com/mtianyan/Artic ...
- django 缓存(memcached)
Django提供了6种缓存方式 开发调试缓存 内存缓存 文件缓存 数据库缓存 Memcache缓存(使用python-memcached模块) Memcache缓存(使用pylibmc模块) 常使用的 ...
随机推荐
- CentOS7中,vnc分辨率设置。
使用geometry参数进行调整 例如,我们需要将分辨率调整到800x600 [root@secdb ~]# vncserver -geometry 800x600 New 'secdb:5 (roo ...
- Thread 1 cannot allocate new log 的处理办法
ALTER SYSTEM ARCHIVE LOG Thread 1 cannot allocate new log, sequence 2594 Checkpoint not complete 这个实 ...
- BZOJ1775: [Usaco2009 Dec]Vidgame 电视游戏问题
n<=50个游戏机有花费,每个游戏机有Gi<=10种游戏,每种游戏有花费有收益,买了游戏机才能玩对应游戏,求最大收益. 这就是一个背包!不过有依存关系,就不会了! 方法一:f[i][j]表 ...
- 出现 Assigning the return value of new by reference is deprecated in xxxx &&“Warning: Call-time pass-by-reference has been deprecated”怎么办?
自从php5.3,越来越多的人会遇到“Assigning the return value of new by reference is deprecated in xxxx”这样的提示,尤其是在国外 ...
- iOS 混合变换旋转 CGAffineTransform
在ios 中, Core Graphics 提供了一系列的函数可以在一个变换的基础上做深层次的变换,如果做一个既要缩放又要旋转的变换,以下的方法比较实用. CGAffineTransformScale ...
- 使用fastjson将list、map转换成json,出现$ref
这是转换时出现的问题情况( map >> json ) 引用是通过"$ref"来表示的 引用 描述 "$ref":".." 上一 ...
- django 简易博客开发 2 模板和数据查询
首先还是贴一下项目地址 https://github.com/goodspeedcheng/sblog 因为代码全在上面 上一篇博客我们介绍了 django的安装配置,新建project,新建a ...
- linux 解压zip文件
linux 解压zip文件 学习了:https://blog.csdn.net/hbcui1984/article/details/1583796 unzip xx.zip
- [RxJS] Create a Reusable Operator from Scratch in RxJS
With knowledge of extending Subscriber and using source.lift to connect a source to a subscriber, yo ...
- Android Studio一些简单设置
简单设置 1.默认主题设置 默认的 Android Studio 为灰色界面,能够选择使用炫酷的黑色界面. Settings --> Appearance --> Them ...