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 为处理完成