DJango-celery
00 min
2024-5-14
2024-5-14
type
status
date
slug
summary
tags
category
icon
password

一、 Django中集成方式一(通用方案)

1.1 把上面的包-复制到djagno项目中

notion image

1.2 在views中编写视图函数

1.3 配置路由

1.4 浏览器访问,提交任务

1.5 启动worker执行任务

1.6 查看任务结果

二 、Django中集成方式二(官方方案)

2.0 安装模块

2.1 在项目目录下新建celery.py

notion image

2.2 在django配置文件中加入

notion image

2.3 在主目录的init.py中添加如下代码

notion image

2.4 在app下新建tasks.py(必须叫tasks.py)

notion image

2.5 实现异步views.py

notion image

2.6 配置路由

总路由urls.py

app自己的路由urls.py

2.7 启动celery

notion image

2.8 浏览器访问-添加任务

notion image

三、 实现定时任务

3.1 settings.py加入

3.2 启动worker和beat

四、通过Admin配置定时任务

通过settings.py的配置可以实现定时任务的配置,做为实际项目中可能还是不够实用,更加工程化的做法是将定时任务的配置放到数据库里通过界面来配置。
Celery对此也提供了很好的支持,这需要安装django-celery-beat插件

4.1 安装djiango-celery-beat

4.2 在APP中注册djiango-celery-beat

4.3 在settings.py中设置调度器及时区

在settings.py中屏蔽到原来的调度器,加入

4.4 设置时区

4.5 数据迁移

4.6 使用admin后台管理插入数据

notion image
notion image

4.7 美化admin

notion image

4.8 增加任务

有多种任务类型可供选择
notion image
  • 设置间隔
notion image
启动worker 和beat

五、 admin监控任务执行情况

在控制台监控任务执行情况,还不是很方便,最好是能够通过web界面看到任务的执行情况,如有多少任务在执行,有多少任务执行失败了等。
这个Celery也是可以做到了,就是将任务执行结果写到数据库中,通过web界面显示出来。
这里要用到django-celery-results插件。
通过插件可以使用Django的orm作为结果存储,这样的好处在于我们可以直接通过django的数据查看到任务状态,同时为可以制定更多的操作

5.1 安装django-celery-results

5.2 配置settings.py,注册app

5.3 修改backend配置,将Redis改为django-db

需要注意的是 一定要写CELERY_RESULT_BACKEND 这个名字不能变

5.4 迁移数据库

5.5 admin 查看

notion image

六、 Flower监控任务执行情况

如果不想通django的管理界面监控任务的执行,还可以通过Flower插件来进行任务的监控。Flower的界面更加丰富,可以监控的信息更全
Flower 是一个用于监控和管理 Celery 集群的开源 Web 应用程序。它提供有关 Celery workers 和tasks状态的实时信息

6.1 修改结果存储为redis

notion image

6.2 安装和启动

6.3 页面查看

notion image

七、任务异常自动告警(邮件或者其他通知

虽然可以通过界面来监控了,但是我们想要得更多,人不可能天天盯着界面看吧,如果能实现任务执行失败就自动发邮件告警就好了。这个Celery当然也是没有问题的。 通过钩子程序在异常的时候触发邮件通知

7.1 tasks.py中加入

7.2 setting中 邮箱配置

用邮箱发信息需要单独在所在的邮箱开通对应的服务

7.3 admin 配置任务

notion image
这里测试只执行一次,勾选一次任务

7.4 执行任务

notion image
并且已经收到了邮件
notion image

八、案例1:爬取技术文章并告警

8.1 编写orm models.py

8.2 数据库迁移

8.2 构建tasks爬虫任务

8.3 以后只需要在后台管理添加定时任务

执行测试
admin页面构建爬虫任务,一次执行 flower、worker、borker
notion image
notion image
notion image
测试成功!
notion image