原因 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缓存页面, 感谢原作者分享。

掌握添加MySQL用戶的方法對於數據庫管理員和開發者至關重要,因為它確保數據庫的安全性和訪問控制。 1)使用CREATEUSER命令創建新用戶,2)通過GRANT命令分配權限,3)使用FLUSHPRIVILEGES確保權限生效,4)定期審計和清理用戶賬戶以維護性能和安全。

chosecharforfixed-lengthdata,varcharforvariable-lengthdata,andtextforlargetextfield.1)chariseffity forconsistent-lengthdatalikecodes.2)varcharsuitsvariable-lengthdatalikenames,ballancingflexibilitibility andperformance.3)

在MySQL中處理字符串數據類型和索引的最佳實踐包括:1)選擇合適的字符串類型,如CHAR用於固定長度,VARCHAR用於可變長度,TEXT用於大文本;2)謹慎索引,避免過度索引,針對常用查詢創建索引;3)使用前綴索引和全文索引優化長字符串搜索;4)定期監控和優化索引,保持索引小巧高效。通過這些方法,可以在讀取和寫入性能之間取得平衡,提升數據庫效率。

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

tostorestringsefliceflicyInmySql,ChooSetherightDataTypeBasedyOrneOrneEds:1)USEcharforFixed-LengthStstringStringStringSlikeCountryCodes.2)UseVarcharforvariable-lengtthslikenames.3)USETEXTCONTENT.3)

選擇MySQL的BLOB和TEXT數據類型時,BLOB適合存儲二進制數據,TEXT適合存儲文本數據。 1)BLOB適用於圖片、音頻等二進制數據,2)TEXT適用於文章、評論等文本數據,選擇時需考慮數據性質和性能優化。

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

mySqlStringDatatAtatPessHouldBechoseBasedondatActarActeristicsAndusecases:1)USEcharforFixed lengthStstringStringStringSlikeCountryCodes.2)usevarcharforvariable-lengtthslikeLikenames.3)usebarnionororvarinyorvarinyorvarybinarydatalgebenedaTalgeextocrabextrapon.4)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver Mac版
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

WebStorm Mac版
好用的JavaScript開發工具