秒杀逻辑

秒杀

前端

<template>

  <div>
    <button @click="handleClick">点我秒杀</button>
  </div>
</template>

<script>
export default {
  name: "Seckill",
  data() {
    return {
      task_id: ''
    }
  },
  methods: {
    handleClick() {
      this.$axios.post('http://127.0.0.1:8000/test/', {
        id: '999'
      }).then(res => {
        this.$message({
          message: res.data.msg,
          type: 'warning'
        });

        let taskId = res.data.task_id
        setInterval(() => {
          this.$axios.get('http://127.0.0.1:8000/test/?task_id=' + taskId).then(res => {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          })
        }, 3000)


      })

    }

  }


}
</script>

<style scoped>

</style>

后端

class TestView(APIView):
    # def post(self, request):
    #     id=request.data.get('id')
    #     # 同步操作:执行秒杀逻辑--》函数--》假设耗时10s---》返回给前端
    #     # res=seckill('1001',id)
    #
    #     # 异步操作--->瞬间就返回了任务id号,这个任务至于做没做,不知道
    #     res=seckill.delay('1001',id)
    #
    #     return APIResponse(msg='您正在排队',task_id=str(res))

    def post(self, request):

        # res=seckill.delay('1001',id)  # 异步任务,立即执行

        ## 延迟10s后发送短信
        # eta传时间对象,到这个时间,再执行
        # from datetime import datetime, timedelta
        # eta = datetime.utcnow() + timedelta(seconds=10)
        # res=send_sms.apply_async(args=('18933333', '9999'), eta=eta)   # 延迟任务
        res = send_sms.apply_async(args=('18933333', '9999'), countdown=5)  # 延迟任务

        return APIResponse(msg='您正在排队', task_id=str(res))

    def get(self, resquest):
        task_id = resquest.GET.get('task_id')
        from celery_task.celery import app
        from celery.result import AsyncResult
        asy = AsyncResult(id=task_id, app=app)
        if asy.successful():
            result = asy.get()
            return APIResponse(msg='秒杀成功')
        elif asy.failed():
            return APIResponse(msg='秒杀失败')
        else:
            return APIResponse(msg='请继续等待')
posted @ 2022-07-15 21:33  Rain_Kz  阅读(64)  评论(0编辑  收藏  举报