温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Django中的异步任务怎么利用celery实现

发布时间:2020-11-27 14:58:33 来源:亿速云 阅读:141 作者:Leah 栏目:开发技术

Django中的异步任务怎么利用celery实现?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

准备

pip安装celery、flower、eventlet

Django中的异步任务怎么利用celery实现

快速接入

1.项目目录的__init__文件

from __future__ import absolute_import

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celerypro import app as celery_app

2.celerypro.py文件

from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'voice_quality_assurance_configure.settings') #修改项目配置文件的地址
app = Celery('voice_quality_assurance_configure') #修改项目目录名称
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('voice_quality_assurance_configure.celeryconfig') #修改celery配置文件的地址
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

3.celeryconfig.py文件,更多配置项,可以查看官方文档。

from kombu import Queue
BROKER_URL = 'amqp://用户名:密码@ip:5672'# 指定 Broker
CELERY_RESULT_BACKEND = 'rpc://用户名:密码@ip:5672'# 指定 Backend
CELERY_TIMEZONE='Asia/Shanghai'# 指定时区,默认是 UTC
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['pickle', 'json']
CELERY_IGNORE_RESULT = True
# CELERY_TIMEZONE='UTC'
CELERY_IMPORTS = (
  # 指定导入的任务模块
  'apps.mission.tasks'
)
CELERY_QUEUES = (
  Queue('default', routing_key='default'), #声明队列和对应路由键
  Queue('worker_queue', routing_key='worker'), #声明队列和对应路由键
)
CELERY_ROUTES = {
  'apps.mission.tasks.createsingletask': {'queue': 'worker_queue', 'routing_key': 'worker'},
}

app代码如何使用

app下新建tasks.py文件,名字一定要是tasks。(我这里是mission app下的tasks.py)

from celery import shared_task
@shared_task()
def createsingletask():
  print(test)

app下views调用如下:(我这里是mission app下的views.py)

from .tasks import createsingletask

createsingletask.apply_async(())

快速测试和监控

启动多个celery worker,-A 指定项目目录, -P 指定方式,我这里以协程方式运行, -n指定name

celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker1
celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker2
celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker3
celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker4
celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker5

启动flower监控

celery flower --broker=amqp://用户名:密码@ip:5672 --broker-api=http://用户名:密码@ip:15672/api/

查看监控,注意这里的监控数据是不持久化的。

看完上述内容,你们掌握Django中的异步任务怎么利用celery实现的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI