用Python的Tornado框架结合memcached页面改善博客性能
作者:C Wong 时间:2023-07-21 09:14:20
原因
Blog是一个更新并不很频繁的一套系统,但是每次刷新页面都要更新数据库反而很浪费资源,添加静态页面生成是一个解决办法,同时缓存是一个更好的主意,可以结合Memcached添加少量的代码进行缓存,而且免去去了每次更新文章都要重新生成静态页面,特别当页面特别多时.
实现
主要通过页面的uri进行缓存,结合tornado.web.RequestHandler的prepare和on_finish方法函数, prepare 主要是请求前执行,on_finish()是请求结束之前执行.在渲染模板时缓存页面内容,然后在请求前检测是否有缓存,如果有直接输出缓存,结束请求,在POST提交之后清空所有缓存,重新生成缓存,从而保证内容实时性.由于登录用户和普通用户的页面不相同,所以不缓存登录用户页面(代码中没有体现,请自行实现).主要python代码(省略了模板渲染的代码):
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Author : cold
# E-mail : wh_linux@126.com
# Date : 13/01/14 09:57:31
# Desc :
#
import config
import pylibmc
from tornado.web import RequestHandler
#### 省略Cache类定义 #####
class Memcached(object):
_mc = pylibmc.client.Client(config.CACHE_HOST, binary = True)
def __enter__(self):
if config.CACHED:
return Memcached
else:
return Cache()
def __exit__(self, exc_type, exc_val, exc_tb):
pass
@classmethod
def get_cache(cls):
return cls._mc
@classmethod
def get(cls, key, default = None):
r = cls._mc.get(key)
if not r:
r = default
return r
@classmethod
def set(cls, key, value, timeout = 0):
timeout = timeout if timeout else config.CACHE_TIMEOUT
return cls._mc.set(key, value, timeout)
@classmethod
def delete(cls, key):
return cls._mc.delete(key)
@classmethod
def flush(cls):
return cls._mc.flush_all()
def __getattr__(self, key):
return Memcached.get(key)
def __setattr__(self, key, value):
return Memcached.set(key, value)
class BaseHandler(RequestHandler):
""" 继承tornado请求基类,重写 prepare和on_finish方法 """
cache = Memcached
def render(self, template_path, *args, **kwargs):
""" 渲染模板 """
# 省略渲染模板代码
content = '' # 渲染模板后的内容
if self.request.method == "GET" and CACHED and \
not self.request.path.startswith("/admin"):
self.cache.set(self.request.uri, content) # 将渲染后的内容缓存起来
self.write(content)
def prepare(self):
super(BaseHandler, self).prepare()
# 如果请求是GET方法,而且不是请求后台
if self.request.method == "GET" and CACHED and \
not self.request.path.startswith("/admin"):
# 尝试获取当前页面的缓存
cache = self.cache.get(self.request.uri)
# 获取缓存则输出页面,结束请求
if cache:
return self.finish(cache)
def on_finish(self):
""" 重写结束请求前的方法函数 """
if self.request.method == "POST":
# 如果遇到POST提交则清空缓存
self.cache.flush()
缓存系统在redis和Memcached选择了很久,因为只是单纯的缓存页面所以最后选择了memcached,使用pylibmc python库.
测试
使用webbench 网站压力测试对比了缓存前后的结果: 使用缓存前
$ webbench -c 500 -t 30 http://www.linuxzen.com/
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Benchmarking: GET http://www.linuxzen.com/
500 clients, running 30 sec.
Speed=54 pages/min, 38160 bytes/sec.
Requests: 27 susceed, 0 failed.
使用缓存后:
$ webbench -c 500 -t 30 http://www.linuxzen.com/
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Benchmarking: GET http://www.linuxzen.com/
500 clients, running 30 sec.
Speed=256 pages/min, 238544 bytes/sec.
Requests: 128 susceed, 0 failed.
明显快了很多...
标签:Python
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Vue组件之间的数据通信实例
2024-06-05 09:20:15
![](https://img.aspxhome.com/file/2023/4/122984_0s.jpg)
解决在Python编辑器pycharm中程序run正常debug错误的问题
2023-09-09 09:58:39
![](https://img.aspxhome.com/file/2023/6/128206_0s.jpg)
日期垂直排列的两种技巧
2009-08-28 12:38:00
![](https://img.aspxhome.com/file/UploadPic/20098/28/01-16s.jpg)
Golang json 库中的RawMessage功能原理
2024-04-30 10:07:27
Python实现自动化域名批量解析分享
2023-01-27 00:04:36
![](https://img.aspxhome.com/file/2023/2/75172_0s.png)
用Python中的__slots__缓存资源以节省内存开销的方法
2021-06-21 10:33:40
![](https://img.aspxhome.com/file/2023/9/134569_0s.jpg)
JavaScript调用ajax获取文本文件内容实现代码
2024-04-30 10:15:52
![](https://img.aspxhome.com/file/2023/7/130467_0s.gif)
SQL SERVER数据库开发之asp存储过程应用
2008-05-19 12:55:00
![](https://img.aspxhome.com/file/UploadPic/up/2008051913142215.jpg)
详解python ThreadPoolExecutor异常捕获
2023-08-09 12:54:30
vue实现全选、反选功能
2024-04-09 10:58:43
![](https://img.aspxhome.com/file/2023/6/139726_0s.png)
ubuntu安装mysql数据库方法
2024-01-13 06:33:53
![](https://img.aspxhome.com/file/2023/9/126279_0s.jpg)
利用色轮选择颜色搭配[译]
2009-10-31 18:24:00
![](https://img.aspxhome.com/file/UploadPic/200910/31/01-56s.jpg)
一张图带我们入门Python基础教程
2021-07-27 14:19:15
![](https://img.aspxhome.com/file/2023/6/115216_0s.png)
PyTorch中model.zero_grad()和optimizer.zero_grad()用法
2023-09-15 20:13:57
![](https://img.aspxhome.com/file/2023/4/71984_0s.jpg)
Python爬虫实现“盗取”微信好友信息的方法分析
2023-01-16 09:37:33
python库skimage给灰度图像染色的方法示例
2021-09-07 14:33:49
![](https://img.aspxhome.com/file/2023/7/114477_0s.jpg)
Python图像处理实现两幅图像合成一幅图像的方法【测试可用】
2022-11-13 08:36:56
![](https://img.aspxhome.com/file/2023/5/104955_0s.png)
SQL附加数据库失败问题的解决方法
2024-01-25 19:22:10
![](https://img.aspxhome.com/file/2023/1/108491_0s.jpg)
MySQL数据库优化技术之索引使用技巧总结
2024-01-21 16:24:22
django haystack实现全文检索的示例代码
2021-04-08 05:00:59
![](https://img.aspxhome.com/file/2023/5/128285_0s.png)