久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Django celery異步任務實現代碼示例

瀏覽:197日期:2024-09-17 15:00:23

最近項目中用到celery很多,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_importimport osfrom celery import Celeryfrom 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 QueueBROKER_URL = ’amqp://用戶名:密碼@ip:5672’# 指定 BrokerCELERY_RESULT_BACKEND = ’rpc://用戶名:密碼@ip:5672’# 指定 BackendCELERY_TIMEZONE=’Asia/Shanghai’# 指定時區,默認是 UTCCELERY_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 worker1celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker2celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker3celery worker -A voice_quality_assurance_configure --loglevel=info -P eventlet -n worker4celery 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
相關文章:
主站蜘蛛池模板: 兴和县| 益阳市| 瓦房店市| 南乐县| 安陆市| 蚌埠市| 独山县| 商城县| 泽普县| 寻乌县| 台东县| 崇仁县| 布尔津县| 新干县| 蒲城县| 锡林郭勒盟| 滕州市| 雷州市| 山西省| 淳化县| 芜湖县| 龙胜| 蓝山县| 驻马店市| 额尔古纳市| 奈曼旗| 莲花县| 蒙山县| 尼玛县| 牡丹江市| 和田市| 长沙县| 错那县| 盐源县| 满洲里市| 奉新县| 侯马市| 仙居县| 黑龙江省| 平山县| 临夏市|