Python Celery 微服务范例

PreRequirements

requirements.txt

1
2
3
4
5
6
celery==4.2.1
Django==1.11.20
django-celery==3.2.2
redis==3.2.0
grpcio==1.19.0
grpcio-tools==1.19.0

Install Dependent Packages

1
2
pyenv activate env_celery_demo
pip install --no-cache-dir -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

Start django project and demo_app

1
2
python manage.py startproject demo
python manage.py startapp demo_app

demo/celery.py

1
2
3
4
5
6
7
8
9
10
11
12
from celery import Celery
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings')

from django.conf import settings

app = Celery('demo')

app.config_from_object('django.conf.settings')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

Add lines in demo/settings.py INSTALLED_APPS

1
2
3
4
5
6
7
8
9
10
11
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'djcelery',
'demo_app',
]

Add lines at bottom of demo/settings.py

1
2
3
4
5
djcelery.setup_loader()
CELERY_TIMEZONE = TIME_ZONE
BROKER_URL = 'redis://:password@127.0.0.1:6379/8'
BROKER_PASSWORD = 'password'
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'

demo_app/tasks.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from demo.celery import app


class AddClass(app.Task):
def run(self):
print('run')


app.tasks.register(AddClass)


@app.task
def demo_task():
print('demo_task')


app.tasks.register(demo_task)

Run celery

1
2
python manage.py celery worker -l info
python manage.py celery beat

Run django

1
python manage.py runserver 0.0.0.0:8000