Distribute Tasks with Celery and RabbitMQ

Celery is an asynchronous task queue(異步任務(wù)隊列).

RabbitMQ is a message broker(消息代理奥务,消息中間件) widely used with Celery.

基本概念

Broker

The Broker (RabbitMQ) is used for dispatching tasks to task queues according to some routing rules, and then delivering tasks from task queues to workers.
Broker (RabbitMQ)按照一定的路由規(guī)則派遣任務(wù)到任務(wù)隊列稽鞭,然后把任務(wù)隊列中的任務(wù)交付給 workers技矮。

Consumer (Celery Workers)

The Consumer is the one or multiple Celery workers executing the tasks. You could start many workers depending on your use case.
Consumer 是一個或多個正在執(zhí)行任務(wù)的 Celery workers烁登。你可以開始許多 workers 根據(jù)您的使用情況净响。

Result Backend

The Result Backend is used for storing the results of your tasks. However, it is not a required element, so if you do not include it in your settings, you cannot access the results of your tasks.
Result Backend 用于存儲你的任務(wù)結(jié)果梧兼。但是蹂窖,它不是必需的元素,因此,如果你的設(shè)置中不包括它疾忍,你便不能訪問你的任務(wù)結(jié)果乔外。

安裝 Celery

pip install celery

選擇 Broker

Why do we need another thing called broker?

It’s because Celery does not actually construct a message queue itself, so it needs an extra(額外的) message transport (a broker) to do that work.

In fact, you can choose from a few different brokers, like RabbitMQ, Redis or a database.

We are using RabbitMQ as our broker because it is feature-complete, stable and recommended by Celery.

啟動 RabbitMQ

You will see similar output if the RabbitMQ server starts successfully.


配置 RabbitMQ

要使用 Celery,我們需要創(chuàng)建一個 RabbitMQ 用戶一罩、一個虛擬主機杨幼,并且允許這個用戶訪問這個虛擬主機:

rabbitmqctl add_user myuser mypassword

rabbitmqctl add_vhost myvhost

rabbitmqctl set_permissions -p myvhost myuser ".*" ".*" ".*"

There are three kinds of operations in RabbitMQ: configure, write and read.

The "." "." ".*" means that the user “myuser” will have all configure, write and read permissions.

A Simple Demo Project

Project Structure
celery_demo
    __init__.py
    celery.py
    tasks.py
    run_tasks.py
celery.py
# -*-coding:utf-8-*-
from __future__ import absolute_import
from celery import Celery


app = Celery('celery_demo',
             broker='amqp://myuser:mypassword@localhost/myvhost',
             backend='rpc://',
             include=['celery_demo.tasks'])

The first argument of Celery is just the name of the project package, which is “celery_demo”.
The broker argument specifies the broker URL, which should be the RabbitMQ we started earlier. Note that the format of broker URL should be: transport://userid:password@hostname:port/virtual_host

For RabbitMQ, the transport is amqp.

The backend argument specifies a backend URL. A backend in Celery is used for storing the task results. So if you need to access the results of your task when it is finished, you should set a backend for Celery.
rpc means sending the results back as AMQP messages, which is an acceptable format for our demo. More choices for message formats can be found here.
The include argument specifies a list of modules that you want to import when Celery worker starts. We add the tasks module here so that the worker can find our task.

tasks.py
# -*-coding:utf-8-*-
from .celery import app
import time


@app.task
def longtime_add(x, y):
    print 'long time task begins'
    time.sleep(5)
    print 'long time task finished'
    return x + y
run_tasks.py
# -*-coding:utf-8-*-
from .tasks import longtime_add
import time

if __name__ == '__main__':
    result = longtime_add.delay(1, 2)
    # at this time, our task is not finished, so it will return False
    print 'Task finished? ', result.ready()
    print 'Task result: ', result.result
    # sleep 10 seconds to ensure the task has been finished
    time.sleep(10)
    print 'Task finished? ', result.ready()
    print 'Task result: ', result.result

Here, we call the task longtime_add using the delay method, which is needed if we want to process the task asynchronously.

Start Celery Worker

Now, we can start Celery worker using the command below (run in the parent folder of our project folder celery_demo):
celery -A celery_demo worker --loglevel=info

You will see something like this if Celery successfully connects to RabbitMQ:


Run Tasks

In another console, input the following (run in the parent folder of our project folder celery_demo):
python -m celery_demo.run_tasks
Now if you look at the Celery console, you will see that our worker received the task:

In the current console, you will see the following output:


This is the expected behavior. At first, our task was not ready, and the result was None. After 10 seconds, our task has been finished and the result is 3.

Monitor Celery in Real Time

Flower is a real-time web-based monitor for Celery. Using Flower, you could easily monitor your task progress and history.

To start the Flower web console, we need to run the following command (run in the parent folder of our project folder celery_demo):
celery -A test_celery flower
Flower will run a server with default port 5555, and you can access the web console at http://localhost:5555.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市聂渊,隨后出現(xiàn)的幾起案子差购,更是在濱河造成了極大的恐慌,老刑警劉巖汉嗽,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件欲逃,死亡現(xiàn)場離奇詭異,居然都是意外死亡饼暑,警方通過查閱死者的電腦和手機暖夭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來撵孤,“玉大人迈着,你說我怎么就攤上這事⌒奥耄” “怎么了裕菠?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長闭专。 經(jīng)常有香客問我奴潘,道長,這世上最難降的妖魔是什么影钉? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任画髓,我火速辦了婚禮,結(jié)果婚禮上平委,老公的妹妹穿的比我還像新娘奈虾。我一直安慰自己,他們只是感情好廉赔,可當(dāng)我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布肉微。 她就那樣靜靜地躺著,像睡著了一般蜡塌。 火紅的嫁衣襯著肌膚如雪碉纳。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天馏艾,我揣著相機與錄音劳曹,去河邊找鬼奴愉。 笑死,一個胖子當(dāng)著我的面吹牛铁孵,可吹牛的內(nèi)容都是我干的躁劣。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼库菲,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了志膀?” 一聲冷哼從身側(cè)響起熙宇,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎溉浙,沒想到半個月后烫止,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡戳稽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年馆蠕,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片惊奇。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡互躬,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出颂郎,到底是詐尸還是另有隱情吼渡,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布乓序,位于F島的核電站寺酪,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏替劈。R本人自食惡果不足惜寄雀,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望陨献。 院中可真熱鬧盒犹,春花似錦、人聲如沸眨业。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽坛猪。三九已至脖阵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間墅茉,已是汗流浹背命黔。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工呜呐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人悍募。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓蘑辑,卻偏偏與公主長得像,于是被迫代替她去往敵國和親坠宴。 傳聞我的和親對象是個殘疾皇子洋魂,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,505評論 0 23
  • 在對android進行開發(fā)時,常常需要用到第三方的jar包喜鼓,例如lite-orm 這里以該包為例講解如何導(dǎo)入 1 ...
    Ry_L閱讀 336評論 0 0
  • 人均餐飲消費7340元 南京吃貨全國第一 來源:新華報業(yè)網(wǎng) 人均餐飲消費7340元 南京吃貨全國第一 南京吃貨的實...
    Terry1018閱讀 378評論 0 0
  • 點開伊洛發(fā)來的照片副砍,是兩個人的背影照。照片很模糊庄岖,只依稀看得清是一對高中生裝扮模樣的男女同學(xué)豁翎。從拍照角度來看,應(yīng)該...
    染墨以待閱讀 515評論 2 3
  • 本文參加#我的軍訓(xùn)我來說#活動,本人承諾背桐,文章內(nèi)容為原創(chuàng)优烧,且未在其他平臺發(fā)表過。 九月的風(fēng)涼爽但...
    隨意取個昵稱閱讀 231評論 0 0