vLog使用Tornado框架结合memcached缓存页面
原因 Blog是一个更新并不很频繁的一套系统,但是每次刷新页面都要更新数据库反而很浪费资源,添加静态页面生成是一个解决办法,同时缓存是一个更好的主意,可以结合Memcached添加少量的代码进行缓存,而且免去去了每次更新文章都要重新生成静态页面,特别当页面特
原因
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.
明显快了很多...
原文地址:vLog使用Tornado框架结合memcached缓存页面, 感谢原作者分享。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The Sony ZV-E10 II has been leaked before as coming in the first half of 2024, and while the initial launch was seemingly set for sometime in May, it was apparently delayed. A new leak shared by prolific leaker Andrea Pizzini, supposedly originating

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

In Go framework development, common challenges and their solutions are: Error handling: Use the errors package for management, and use middleware to centrally handle errors. Authentication and authorization: Integrate third-party libraries and create custom middleware to check credentials. Concurrency processing: Use goroutines, mutexes, and channels to control resource access. Unit testing: Use gotest packages, mocks, and stubs for isolation, and code coverage tools to ensure sufficiency. Deployment and monitoring: Use Docker containers to package deployments, set up data backups, and track performance and errors with logging and monitoring tools.
