分布式任务队列Celery配置
我一般是把Django和Delery搭配使用,项目中的定时任务和异步任务都交给Celery使用。
Celery几种配置方式
使用第三方库
djcelery
,优点是可以在admin后台管理任务,修改任务后,不用重启Celery服务,就可自动更改配置在Django的每个APP目录下创建任务文件,在
settings.py
中配置Celery,优点是简单把任务文件和配置文件放在独立的目录下,优点是减少和Django的耦合
Celery配置-独立目录
1、新建目录celery_prj
,并创建一下四个个文件
(venv) [root@ celery_prj]# tree
.
├── celeryconfig.py
├── celery.py
├── __init__.py
├── tasks.py
2、在celery.py
中创建一个应用
# -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import os
from celery import Celery
# 加入django环境, 在tasks添加不起作用
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oee.settings')
app = Celery('celery_pri.tasks')
app.config_from_object('celery_prj.celeryconfig')
3、在tasks.py
文件中定义任务
from celery_prj.celery import app
@app.task
def add(x, y):
return x + y
4、在celeryconfig.py
中配置Celery
from kombu import Exchange, Queue
from datetime import timedelta
from celery.schedules import crontab
# 配置时区
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_BROKER = 'amqp://guest@localhost//'
CELERY_BACKEND = 'redis://127.0.0.1:6379/6'
# 定义一个默认交换机
default_exchange = Exchange('default', type='direct')
# 定义一个媒体交换机
oee_exchange = Exchange('oee', type='direct')
# 创建二个队列,一个是默认队列,一个是oee
CELERY_QUEUES = (
Queue('default', default_exchange, routing_key='default'),
Queue('oee_web', oee_exchange, routing_key='oee_web'),
)
CELERY_DEFAULT_QUEUE = 'default' # 默认的队列
CELERY_DEFAULT_EXCHANGE = 'default' # 默认的交换机名字为 tasks
CELERY_DEFAULT_ROUTING_KEY = 'default' # 默认的路由键是 default
# CELERY_TASK_SERIALIZER = 'json'
# CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] # 指定一种 "msgpack, json, pickle..."
CELERYD_MAX_TASKS_PER_CHILD = 10 # celery worker执行10个任务后销毁,防止内存泄漏,待实验
# CELERYD_LOG_FILE = BASE_DIR + "/logs/celery/celery.log" # log路径
# CELERYBEAT_LOG_FILE = BASE_DIR + "/logs/celery/beat.log" # beat log路径
CELERY_ROUTES = (
{
'tasks.add': {
'queue': 'default',
'routing_key': 'default'
}
}
)
CELERYBEAT_SCHEDULE = {
'add-every-5-seconds': {
'task': 'celery_prj.tasks.add',
# 'schedule': crontab(minute=u'10', hour=u'12',),
'schedule': timedelta(seconds=3),
'args': (16, 16)
},
}
# https://stackoverflow.com/questions/9769496/celery-received-unregistered-task-of-type-run-example
# 在出现worker接受到的message出现没有注册的错误,加入以下语句
CELERY_IMPORTS = ("celery_prj.tasks", )
5、启动Celery worker和beat
celery -A /path/to/celery_prj worker -l info
celery -A /path/to/celery_prj beat -l info