1、安装

因为celery4.0不支持window,若是在window上安装celery4.0将会出现下面的错误
flask_cleryflask_cleryhtml

你如今只能安装
pip install celery==3.1
python

2、安装py for redis 模块

pip install redisgit

3、安装redis服务

网上不少文章都写得模棱两可,把人坑的不要不要的!!!

Redis对于Linux是官方支持的,可是不支持window,网上不少做者写文章都不写具体的系统环境,大多数直接说pip install redis就可使用redis了,真的是坑人的玩意,本人深受其毒害github

对于windows,若是你须要使用redis服务,那么进入该地址下载
https://github.com/MSOpenTech/redis/releases

redis安装包,双击完成就能够了web

若是你在window上不安装该redis包,将会提示

redis.exceptions.ConnectionError: Error 10061 connecting to localhost:6379.

或者

redis.exceptions.ConnectionError redis

须要注意是:安装目录不能安装在C盘,不然会出现权限依赖错误flask

4、添加redis环境变量

D:\Program Files\Rediswindows

5、初始化redis

进入redis安装目录,打开cmd运行命令redis-server.exe redis.windows.conf,若是出错服务器

  • 双击目录下的redis-cli.exe
  • 在出现的窗口中输入shutdown
  • 继续输入exit

6、lask 集成celyer

在Flask配置中添加配置

1
2
3
 # Celery 配置
CELERY_BROKER_URL = 'redis://localhost:6379/0' # broker是一个消息传输的中间件
CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' # 任务执行器
  • 在flask工程的__init__目录下生产celery实例
    注意!!如下代码必须在 flask app读取完配置文件后编写,不然会报错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def make_celery(app):
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'],
backend=app.config['CELERY_RESULT_BACKEND'])
celery.conf.update(app.config)
TaskBase = celery.Task

class ContextTask(TaskBase):
abstract = True

def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)

celery.Task = ContextTask
return celery


celery = make_celery(app)

完整示例以下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
app = Flask(__name__)
app.config.from_object(config['default'])

def make_celery(app):
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'],
backend=app.config['CELERY_RESULT_BACKEND'])
celery.conf.update(app.config)
TaskBase = celery.Task

class ContextTask(TaskBase):
abstract = True

def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)

celery.Task = ContextTask
return celery


celery = make_celery(app)

一份比较经常使用的配置文件

# 注意,celery4版本后,CELERY_BROKER_URL改成BROKER_URL
BROKER_URL = 'amqp://username:passwd@host:port/虚拟主机名'
# 指定结果的接受地址
CELERY_RESULT_BACKEND = 'redis://username:passwd@host:port/db'
# 指定任务序列化方式
CELERY_TASK_SERIALIZER = 'msgpack' 
# 指定结果序列化方式
CELERY_RESULT_SERIALIZER = 'msgpack'
# 任务过时时间,celery任务执行结果的超时时间
CELERY_TASK_RESULT_EXPIRES = 60 * 20   
# 指定任务接受的序列化类型.
CELERY_ACCEPT_CONTENT = ["msgpack"]   
# 任务发送完成是否须要确认,这一项对性能有一点影响     
CELERY_ACKS_LATE = True  
# 压缩方案选择,能够是zlib, bzip2,默认是发送没有压缩的数据
CELERY_MESSAGE_COMPRESSION = 'zlib' 
# 规定完成任务的时间
CELERYD_TASK_TIME_LIMIT = 5  # 在5s内完成任务,不然执行该任务的worker将被杀死,任务移交给父进程
# celery worker的并发数,默认是服务器的内核数目,也是命令行-c参数指定的数目
CELERYD_CONCURRENCY = 4 
# celery worker 每次去rabbitmq预取任务的数量
CELERYD_PREFETCH_MULTIPLIER = 4 
# 每一个worker执行了多少任务就会死掉,默认是无限的
CELERYD_MAX_TASKS_PER_CHILD = 40 
# 设置默认的队列名称,若是一个消息不符合其余的队列就会放在默认队列里面,若是什么都不设置的话,数据都会发送到默认的队列中
CELERY_DEFAULT_QUEUE = "default" 
# 设置详细的队列
CELERY_QUEUES = {
    "default": { # 这是上面指定的默认队列
        "exchange": "default",
        "exchange_type": "direct",
        "routing_key": "default"
    },
    "topicqueue": { # 这是一个topic队列 凡是topictest开头的routing key都会被放到这个队列
        "routing_key": "topic.#",
        "exchange": "topic_exchange",
        "exchange_type": "topic",
    },
    "task_eeg": { # 设置扇形交换机
        "exchange": "tasks",
        "exchange_type": "fanout",
        "binding_key": "tasks",
    },
    
}

 

在cmd中启动celery服务

执行命令celery -A your_application.celery worker loglevel=info,your_application为你工程的名字,在这里为 get_tieba_film

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@app.route('/')
@app.route('/index')
def index():
print ("耗时的任务")
# 任务已经交给异步处理了
result = get_film_content.apply_async(args=[1])
# 若是须要等待返回值,可使用get()或wait()方法
# result.wait()
return '耗时的任务已经交给了celery'


@celery.task()
def get_film_content(a):
util = SpiderRunUtil.SpiderRun(TieBaSpider.FilmSpider())
util.start()

绑定

一个绑定任务意味着任务函数的第一个参数老是任务实例自己(self),就像 Python 绑定方法相似:并发

1
2
3
@task(bind=True) 
def add(self, x, y):
logger.info(self.request.id)

 

任务继承

任务装饰器的 base 参数能够声明任务的基类

1
2
3
4
5
6
7
import celery
class MyTask(celery.Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
print('{0!r} failed: {1!r}'.format(task_id, exc))
@task(base=MyTask)
def add(x, y):
raise KeyError()

 

任务名称

每一个任务必须有不一样的名称。
若是没有显示提供名称,任务装饰器将会自动产生一个,产生的名称会基于这些信息:
1)任务定义所在的模块,
2)任务函数的名称

显示设置任务名称的例子:

1
2
3
4
5
>>> @app.task(name='sum-of-two-numbers')
>>> def add(x, y):
... return x + y
>>> add.name
'sum-of-two-numbers'

最佳实践是使用模块名称做为命名空间,这样的话若是有一个同名任务函数定义在其余模块也不会产生冲突。

1
2
3
>>> @app.task(name='tasks.add')
>>> def add(x, y):
... return x + y

 

7、安装flower

将各个任务的执行状况、各个worker的健康状态进行监控并以可视化的方式展示

1
pip install flower

 

启动flower(默认会启动一个webserver,端口为5555):

1

 

指定broker并启动:

celery flower --broker=amqp://guest:guest@localhost:5672//  或
celery flower --broker=redis://guest:guest@localhost:6379/0

 

 

进入http://localhost:5555便可查看。

doc

8、常见错误

1
ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0:

缘由是:redis-server 没有启动
解决方案:到redis安装目录下执行redis-server.exe redis.windows.conf
检查redis是否启动:redis-cli ping

1
line 442, in on_task_received

解决:

1
2
3
4
5
6
7
8
9
10
Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://bit.ly/gLye1c for more information.
The full contents of the message body was:
{'timelimit': (None, None), 'utc': True, 'chord': None, 'args': [4, 4], 'retries': 0, 'expires': None, 'task': 'main.add', 'callbacks': None,
'errbacks': None, 'taskset': None, 'kwargs': {}, 'eta': None, 'id': '97000322-93be-47e9-a082-4620e123dc5e'} (210b)
Traceback (most recent call last):
File "d:\vm_env\flask_card\lib\site-packages\celery\worker\consumer.py", line 442, in on_task_received
strategies[name](message, body,
KeyError: 'main.add'

缘由:任务没有注册或注册不成功,只有在启动的时候提示有任务的时候,才能使用该任务
flask_celeryflask_celery
解决:

  1. 你在那个类中使用celery就在哪一个类中执行celery -A 包名.类名.celery worker -l info
  2. 根据上一部提示的任务列表给任务设置对应的名称
    如在Test中
1
2
3
4
5
6
from main import app, celery

@celery.task(name="main.Test.add".)
def add(x, y):
print "ddddsws"
return x + y

目录结构:

1
2
3
4
5
6
+ Card  # 工程
+ main
+ admin
- Task.py
- __init__.py
- Test.py

 

则应该启动的命令为:

1
celery -A main.Test.celery worker -l info

 

同时,若是你的Task.py也有任务,那么你还应该从新建立一个cmd窗口执行

1
celery -A main.admin.Task.celery worker -l info

 

celery的工做进程能够建立多个
flask_celeryflask_celery
flask_celeryflask_celery

 

参考:

https://www.laoyuyu.me/2018/02/10/python_flask_celery/

https://www.cnblogs.com/cwp-bg/p/8759638.html

celery用户指南,强烈推荐看

redis安装

celery使用
https://redis.io/topics/quickstart

http://einverne.github.io/post/2017/05/celery-best-practice.html  Celery 最佳实践 

http://orangleliu.info/2014/08/09/celery-best-practice/  Celery最佳实践-正确使用celery的7条建议