在质量度量平台中,有少数几个页面打开速度是很慢的(不过由于用户量不大,以前也没关注),原因是需要对大量的数据做运算分析才展现出结果,这几天做了一下优化。方法很简单,这几个很慢的页面都是只读的数据,使用memcached缓存一下数据,效果会非常的好。
Django中很方便使用Cache,先需要安装python-memcached这个python包,在settings.py文件中添加如下内容:
| 
					 1 2 3 4 5 6  | 
						CACHES = {     'default': {         'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',         'LOCATION': '192.168.1.2:11211',     } }  | 
					
其中192.168.1.2:11211就是搭建的memcached服务(搭建方法也比较简单)。
然后在代码中,先去cache中取一下,如果没有取到,就重新从原始取到获取数据即可。例如下面的代码片段:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  | 
						from django.core.cache import cache def get_web_status(start, end):     '''     @summary: get the web HTTP status data.               it will call the remote AEW (in product env).     @param start: the start date.  Not used yet.     @param end: the end date.  Not used yet.     @return: a list of the web HTTP status count data.     '''     key = 'weekly_web_status'     ret = cache.get(key)     if not ret:         try:             remote_api = 'http://10.1.1.2:8080/api/remote/weekly_web_status'             days = 7             remote_url = '%s?days=%s' % (remote_api, days)             doc = urllib.urlopen(remote_url)             ret = json.loads(doc.read())['detail']             cache.set(key, ret, 1*3600)         except:             pass     return ret  | 
					
由于我的数据是从DW部门来过来的,这部分是每天更新一次的数据,对稍微的延迟不敏感,cache设置的过期时间是1小时。
另外,还在后台有个job在每天凌晨就去获取最新的数据并set到memcached中,这样每天第一个人访问时也不会太慢。
使用了Cache效果非常明显,以其中一个API为例,测试数据如下:

在没有使用cache时,这个页面去调用外部的API(进行的是实时计算统计分析),响应时间在30s左右(⊙﹏⊙b汗),使用cache后缩短为6ms;在使用1个并发压测的情况下,TPS提升300倍。100并发时,使用memcached的API的TPS达到866,还不错的~ (服务跑在4核4GB内存的虚拟机上)。