Django框架中,使用celery实现异步

作用:在使用框架时,在视图函数中实现异步
构成:
任务task:一段耗时并与响应结果无关的代码,如发短信
工人worker:新进程,用于执行任务代码
代理人broker:调用任务时,将任务添加到队列中,通知worker执行
队列queue:用于存储待执行的任务

调用:任务函数.delay(参数)

说明:定义任务函数的文件tasks.py,文件名是固定的
实现步骤:
1.在项目目录下,新建包celery_tasks用于保存celery异步任务
2.在celery_tasks包下新建config.py,指定代理人,用于保存celery的配置信息

# 指定使用redis作为代理人,将来,redis会存储待执行任务队列
broker_url = 'redis://127.0.0.1:6379/14'

3.在celery_tasks包下新建main.py,创建celery对象,配置自动识别任务,用于作为celery的启动文件

from celery import Celery

# 为celery使用django配置文件进行设置
import os
os.environ['DJANGO_SETTINGS_MODULE'] = '(项目settings地址)'

# 创建celery应用,Celery(‘名字可随意’)
app = Celery('taobao')

# 导入celery配置
app.config_from_object('celery_tasks.config')

# 自动注册celery任务
app.autodiscover_tasks([
    'celery_tasks.sms_code',
]) 

4.在celery_tasks新建包,如sms_code

5.在celery_tasks/sms_code/下创建tasks.py,用于保存发送短信的异步任务
6.定义方法,封装耗时代码,添加装饰器

from celery_tasks.main import app

@app.task(name='send_sms_code')
def send_sms_code(code):
    # 定义方法,封装耗时代码
    print(code)

7.在main.py中注册
8.启动工人,如果代码发生改变,需要重启任务
9.在视图函数中调用verifications/views.py:任务方法.delay(参数)(这里没有调用第三方接口发短信,只是打印出验证码)

  

class SmsView(APIView):
    # 接收手机号,发短信
    def get(self, request, mobile):
        # 连接redis,指定cache中的键
        redis_cli = get_redis_connection('sms_code')

        # 1.验证是否向此手机号发过短信,如果发过则返回提示
        if redis_cli.get('sms_flag_' + mobile):
            return Response({'message': '已经发送'})

        # 2.如果未发过,则发短信
        # 2.1生成随机6位数
        sms_code = random.randint(100000, 999999)

        # 优化,只与redis交互一次
        redis_pipeline = redis_cli.pipeline()
        redis_pipeline.setex('sms_' + mobile, constants.SMS_CODE_EXPIRES, sms_code)
        redis_pipeline.setex('sms_flag_' + mobile, constants.SMS_FLAG_EXPIRES, 1)
        redis_pipeline.execute()

        # 2.4发短信,可以调用第三方短信平台发短信
        # print(sms_code)
        send_sms_code.delay(sms_code)

        # 3.响应
        return Response({'message': 'OK'})

  

10.启动celery服务

执行命令

celery -A celery_tasks.main worker -l info

  

猜你喜欢

转载自www.cnblogs.com/omak/p/10082151.html