Celery異步分佈式python
什麼是celery?redis
他是一個python開發的異步分佈式任務調度模塊數據庫
celery自己不提供消息服務,使用第三方服務,也就是broker來傳遞任務,目前支持rabbitmq,redis,數據庫等等。服務器
咱們使用redisapp
鏈接URL的格式爲:異步
redis://:password@hostname:port/db_number
例如:分佈式
BROKER_URL='redis://localhost:6379/0'
過程如圖示code
在python裏面若是用到異步分佈式,首先想到celery對象
安裝celeryblog
pip install celery pip install redis #以前講過
在服務器上安裝redis服務器,並啓動redis
第一個簡單的例子:
[root@localhost celery]# cat lili.py #/usr/bin/env python #-*- coding:utf-8 -*- from celery import Celery broker="redis://192.168.48.131:6379/5" backend="redis://192.168.48.131:6379/6" app = Celery("lili", broker=broker, backend=backend) @app.task def add(x, y): return x+y
啓動:
# celery -A lili worker -l info
調用:
# cat demo2.py #!/usr/bin/python #-*- coding:utf-8 -*- from lili import add import time a = add.delay(10, 20) print (a) ##返回異步分佈式的對象 print (type(a)) time.sleep(1) print (a.result) ##返回調用的值 print (a.status) ##返回狀態 print (a.get(timeout=3)) ##得到值 print (a.ready()) #是否處理,返回 True 爲處理完成