django下celery的使用
前言
今天在使用django做后台的时候,遇到了这样的问题:django在处理用户请求的时候,需要进行一个耗时较长的异步抓取操作,同时希望能立即给用户返回数据,使用常规的daemon进程的方式没有解决该问题,用力Google了一下发现如下解答:
In fact Django have a syncronous model. If you want to do real async processing, you need a message queue. The most used with django is celery, it may look a bit “overkill” but it’s a good answer.
Why do we need this? because in a wsgi app, apache give the request to the executable, and, the executable returns text. It’s only once when the executable finish his execution that apache aknowledge the end of the request.
celery安装
官网:http://www.celeryproject.org/,celery利用python编写,实现了分布式的消息队列。安装如下:
1 |
|
此外,celery需要方案来实现发送和接收消息,通常通过一种message broker
的独立服务来完成,我们安装官方推荐的RabbitMQ
1 |
|
celery介绍
首先,我们需要创建一个celery的实例,编写文件tasks.py
1 |
|
第一个参数tasks
是当前模块的名称,第二个参数指定了所使用的message broker
的URL,上使用的是RabbitMQ
默认URL
启动celery work进程
1 |
|
调用task
1 |
|
celery在django的使用
整体框架如下:
1 |
|
官方教程已经足够详细了在此就不在累述了 ;-),请戳:http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
附:supervise介绍
嗯,插入supervise的介绍方便之后在后台运行celery实例。因为我厂大规模使用supervise管理服务程序,所以,有必要好好了解一下了
supervise是开源工具集daemontools其中的一个工具
工作原理
supervise启动的时候fork一个子进程,子进程执行execvp系统调用,将自己替换成执行的模块,
模块变成supervise的子进程在运行,而supervise则死循环运行,并通过waitpid或者wait3系统调用选择非阻塞的方式去侦听子进程的运行情况,
当然同时也会读取pipe文件svcontrol的命令,然后根据命令去执行不同的动作,
如果子进程因某种原因导致退出,则supervise通过waitpid或者wait3获知,并继续启动模块,如果模块异常导致无法启动,则会使supervise陷入死循环,不断的启动模块。
安装
1 |
|
用法
1 |
|
supervise switches to the directory named s
and starts ./run
. It restarts ./run
if ./run
exits. It pauses for a second after starting ./run
, so that it does not loop too quickly if ./run
exits immediately.
If the file s/down
exists, supervise does not start ./run
immediately. You can use svc
to start ./run
and to give other commands to supervise.
supervise maintains status information in a binary format inside the directory s/supervise
, which must be writable to supervise. The status information can be read by svstat.
supervise may exit immediately after startup if it cannot find the files it needs in s
or if another copy of supervise is already running in s
. Once supervise is successfully running, it will not exit unless it is killed or specifically asked to exit. You can use svok
to check whether supervise is successfully running. You can use svscan
to reliably start a collection of supervise processes.
supervise 切换到名为 s
的目录并启动 ./run
。如果 ./run
退出,它会重新启动 ./run
。在启动 ./run
后,它会暂停一秒,以防 ./run
立即退出导致循环过快。
如果文件 s/down
存在,supervise 不会立即启动 ./run
。你可以使用 svc
来启动 ./run
并向 supervise 发送其他命令。
supervise 以二进制格式在目录 s/supervise
中维护状态信息,该目录必须对 supervise 可写。svstat 可以读取这些状态信息。
如果在 s
中找不到所需文件,或者已经有另一份 supervise 在 s
中运行,supervise 可能会在启动后立即退出。一旦 supervise 成功运行,除非被终止或明确要求退出,否则它不会退出。你可以使用 svok
检查 supervise 是否成功运行。你可以使用 svscan
可靠地启动一组 supervise 进程。