使用Python Django-nonrel开发GAE应用之使用taskqueue处理缓存,提高性能
task queue
顾名思义,就是任务队列,Google App Engine的中文文档里面没有这一项,(可能是因为目前还处于labs里面的Experimental状态,不会重点介绍)但是我觉得还是有用。大家不妨看看英文文档: http://code.google.com/intl/en/appengine/docs/python/taskqueue/
使用场合
刚刚说到有用,我用在什么地方呢?就是处理缓存。
我们上篇说到我们处理缓存通过cron来定期处理,但是我们知道cron是要写清楚每条地址的,如果我们想把数据的1000个分页都缓存好,一次缓存完是不行的,因为30秒的限制,只能分开缓存,是不是要在cron里面写1000条?那太蠢了。我们就用task queue来做。
使用方法
-
配置taskqueue
-
需要queue.yaml文件(参考:http://code.google.com/intl/en/appengine/docs/python/config/queue.html)
-
queue: - name: default rate: 1/s - name: mail-queue rate: 2000/d bucket_size: 10 - name: background-processing rate: 5/s
-
添加taskqueue的代码
from google.appengine.api.labs import taskqueue taskqueue.add(url='/path/to/my/worker') taskqueue.add(url='/path?a=b&c=d', method='GET')
管理 taskqueue地址
管理地址在: /_ah/admin/queues ,比如:http://localhost:8000/_ah/admin/queues
应用举例
#viewaddtask.py def add_task(request,task=None,*qp): if (task): task = task.strip() if (task=='taskqueue'): ... result_all = '' for category in catelist: for infotype in typelist: for location in locationlist: for date_one in datelist: # Add the task to the default queue. myurl = '/proj/task/cache_page_non_force/%s-%s-%s-%s-%s-%s-%s/'%(category,infotype,location,date_one['year'],date_one['month'],date_one['day'],'1') taskqueue.add(url=myurl,method='GET') result_all = result_all +'<br/>'+ myurl return HttpResponse(result_all)
BUG?错误?
我曾经使用 taskqueue.add(url=myurl) ,发现返回403错误,
然后我改为使用taskqueue.add(url=myurl,method='GET'),才能成功。