python celery 模块

Celery是基于Python开发的一个分布式任务队列框架,支持使用任务队列的方式在分布的机器/进程/线程上执行任务调度
python celery 模块
Celery是典型的生产生-消费者模式,主要由三部分组成:broker(消息队列)、workers(消费者:处理任务)、backend(存储结果)


django + celery 实现任务的异步处理
1.Django Web中从一个http请求发起,到获得响应返回html页面的流程大致如下:http请求发起 -- http handling(request解析) -- url mapping(url正则匹配找到对应的View) -- 在View中进行逻辑的处理、数据计算(包括调用Model类进行数据库的增删改查)--将数据推送到template,返回对应的template/response
同步请求:所有逻辑处理、数据计算任务在View中处理完毕后返回response。在View处理任务时用户处于等待状态,直到页面返回结果
异步请求:View中先返回response,再在后台处理任务。用户无需等待,可以继续浏览网站。当任务处理完成时,我们可以再告知用户
2.建立消息队列
消息队列可以使用RabbitMQ、Redis 等
3.安装django-celery
pip install celery django-celery
4.配置settings.py
import djcelery
djcelery.setup_loader()
BROKER_URL= 'amqp://guest@localhost//'
CELERY_RESULT_BACKEND = 'amqp://guest@localhost//'
其中,当djcelery.setup_loader()运行时,Celery便会去查看INSTALLD_APPS下包含的所有app目录中的tasks.py文件,找到标记为task的方法,将它们注册为celery task
5.在要使用该任务队列的app根目录下(比如qv),建立tasks.py
from celery import taskbr/>@task
def test(x,y):
result = int(x) + int(y)
return result

在tasks.py中我们就可以编码实现我们需要执行的任务逻辑,在开始处import task,然后在要执行的任务方法开头用上装饰器@task。需要注意的是,与一般的.py中实现celery不同,tasks.py必须建在各app的根目录下,且不能随意命名
6.生产任务
在需要执行该任务的View中,通过test.delay的方式来创建任务,并送入消息队列
def produce():
a =1
b =2
r = test.delay(a,b)
7.启动work
#先启动服务器 python manage.py runserver
#再启动worker python manage.py celery worker -c 4 --loglevel=info

猜你喜欢

转载自blog.51cto.com/weadyweady/2322549