celery有多坑,能坑的你亲妈都不认识,信我!!!
声明:代码是从项目中截取的, 为进行测试
使用Celery任务队列,Celery 只是一个任务队列,需要一个broker媒介,将耗时的任务传递给Celery任务队列执行,执行完毕将结果通过broker媒介返回。官方推荐使用RabbitMQ作为消息传递,redis也可以
一、Celery 介绍:概念网上一搜一堆,自己百度去
注意:
1、当使用RabbitMQ时,需要按照pika第三方库,pika0.10.0存在bug,无法获得回调信息,需要按照0.9.14版本即可
2、tornado-celery 库比较旧,无法适应Celery的最新版,会导致报无法导入task Producter包错误,只需要将celery版本按照在3.0.25就可以了
二、安装、配置
python版本3.5.4 别用3.6, 也别用3.7,很多不支持,巨坑无比
redis 5.0.8.msi ----------- rabbitmq 这个应该没什么差异
pip install redis
pip3 install tornado==5.1.1 或者4.1
pip3 install celery==3.1
pip3 install pika==0.9.14
pip3 install tornado-celery
三、window下面测试最简单celery有返回值的实例--时间:2020/7/17
用redis和rabbitmq效率差的不是一点半点
tasks.py
from celery import Celery
#配置好celery的backend和broker
# app = Celery('tasks', backend='redis://localhost:6379/0', broker='redis://localhost:6379/0')
# app = Celery('tasks', backend='redis://localhost:6379', broker='redis://localhost:6379')
app = Celery('tasks', backend='amqp://localhost:5672', broker='amqp://localhost:5672')
# app.conf.CELERY_RESULT_BACKEND = "redis://localhost:6379/0"
# app.conf.CELERY_RESULT_BACKEND = "redis"
# app.conf.CELERY_ACCEPT_CONTENT = ['application/json']
# app.conf.CELERY_TASK_SERIALIZER = 'json'
# app.conf.CELERY_RESULT_SERIALIZER = 'json'
# app.conf.BROKER_HEARTBEAT = 30
# app.conf.CELERY_IGNORE_RESULT = False # this is less important
@app.task #普通函数装饰为 celery task
def add(x, y):
return x + y
#trigger.py
import time
from tasks import add
a = time.time()
result = add.delay(4, 4) #不要直接 add(4, 4),这里需要用 celery 提供的接口 delay 进行调用
# result = add.apply_async((4, 4)) #不要直接 add(4, 4),这里需要用 celery 提供的接口 apply_async 进行调用
print(result.ready())
# while not result.ready():
# time.sleep(1)
print('task done: {0}'.format(result.get()))
print(time.time() - a)