美文网首页
django异步通信框架Celery

django异步通信框架Celery

作者: 不能没有音乐 | 来源:发表于2021-06-23 17:25 被阅读0次

Celery 是一个简单、灵活且可靠的,处理大量消息的 分布式系统。
专注于实时处理的 异步任务队列。
同时也支持 任务调度。

1.安装

pip install Django-celery==3.2.2 
pip install Django-redis  
pip install redis==2.10.6 
# 如果redis版本过高后面会出现错误下面这个
#'str' object has no attribute 'items' (ven) 

2.setting.py配置

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    # 异步
    'djcelery',
]

3.在settings.py同级下创建celery.py和tasks.py

celery:celery的配置
tasks:异步任务
celery.py

from celery import Celery, platforms
from django.conf import settings
import os

# 设置celery的默认工作目录
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djearth.settings")
# 启动celery项目(要加入broker,如果用的是redis的话,不然默认开启的是rabbitmq-server)
app = Celery(broker='redis://localhost:6379/3')
# 项目加载配置
app.config_from_object("django.conf:settings")
# 加载djcelery
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# 支持以root启动
platforms.C_FORCE_ROOT = True

tsaks.py

from .celery import app
import time

@app.task
def task1():
    """无参方法"""
    print("task1...begin...")
    time.sleep(10)  # 模拟耗时操作
    print("task1...end...")

@app.task
def task2(a, b):
    """有参方法"""
    print("task2...begin...a={},b={}".format(a, b))
    time.sleep(10)  # 模拟耗时操作
    print("task2...end...")
    return a + b    

4.在views.py调用

from .tasks import task2
task2.delay(5,5)

5.控制台启动celery

启动服务的命令:
xxxx 为项目名称
celery -A xxxx beat -l info 定时任务
celery -A xxxx worker -l info 异步任务

守护进程方式启动,日志记录在celerylog.log里
celery multi start w1 -A xxxx -l info --logfile = celerylog.log --pidfile = celerypid.pid
停止:celery multi stop w1 -A xxxx -l info
重启:celery multi restart w1 -A xxxx -l info

出现的错误

1.SyntaxError: invalid syntax

报错:python3将async这个单词定义为关键词,所以不可以作为模块名称,需要对源码修改。
修改kombu中的async文件名为asynchronous
然后修改报错的文档中所有的async为asynchronous
https://blog.csdn.net/weixin_44420527/article/details/108877096

2.consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Con

celery.py文件中配置

app = Celery(broker='redis://localhost:6379/3')

3.'str' object has no attribute 'items' (ven)

redis版本太高

pip uninstall redis
pip install redis==2.10.6

4.No module named 'celery.five'

celery降级到4.4.7

使用命令卸载:
pip uninstall celery
重新安装:
pip install celery==4.4.7

参考文章:
https://blog.csdn.net/sanyuedexuanlv/article/details/88052884
https://blog.csdn.net/weixin_44420527/article/details/108877096
https://blog.csdn.net/weixin_44110998/article/details/103498932
https://blog.csdn.net/Coxhuang/article/details/86921407

相关文章

网友评论

      本文标题:django异步通信框架Celery

      本文链接:https://www.haomeiwen.com/subject/fjjbyltx.html