django 使用celery 實現異步任務

celery

情景:用戶發起request,並等待response返回。在本些views中,可能須要執行一段耗時的程序,那麼用戶就會等待很長時間,形成很差的用戶體驗,好比發送郵件、手機驗證碼等。html

使用celery後,狀況就不同了。解決:將耗時的程序放到celery中執行。python

celery官方網站: href="http://www.celeryproject.org/web

celery中文文檔: href="http://docs.jinkan.org/docs/celery/redis

celery名詞:django

  • 任務task:就是一個Python函數。
  • 隊列queue:將須要執行的任務加入到隊列中。
  • 工人worker:在一個新進程中,負責執行隊列中的任務。
  • 代理人broker:負責調度,在佈置環境中使用redis。

示例中使用到的安裝包版本瀏覽器

celery==3.1.25
django-celery==3.1.17

示例

1)在應用question_help/views.py文件中建立視圖sayhello。服務器

import time

def sayhello(request):
    print('hello ...')
    time.sleep(2)
    print('world ...')
    return HttpResponse("hello world")

2)在question_help/urls.py中配置。函數

    url(r'^sayhello$',views.sayhello),

3)啓動服務器,在瀏覽器中輸入以下網址:網站

http://127.0.0.1:8000/sayhello/

4)在終端中效果,兩次輸出之間等待一段時間纔會返回結果。url

5)在settings.py中註冊celery應用

INSTALLED_APPS = (
  ...
  'djcelery',
}

6)在settings.py文件中配置代理和任務模塊。

import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/2' 

7)在應用question_help/目錄下建立tasks.py文件。

import time
from celery import task

@task
def sayhello():
    print('hello ...')
    time.sleep(2)
    print('world ...')

8)打開question_help/views.py文件,修改sayhello視圖以下:

from booktest import tasks
...
def sayhello(request):
    # print('hello ...')
    # time.sleep(2)
    # print('world ...')
    tasks.sayhello.delay()
    return HttpResponse("hello world")

 9)執行遷移生成celery須要的數據表。

python manage.py migrate

生成表以下:

10)啓動Redis,若是已經啓動則不須要啓動。

sudo service redis start

11)啓動worker。

python manage.py celery worker --loglevel=info

啓動成功後提示以下圖:

11)打開新終端,進入虛擬環境,啓動服務器,刷新瀏覽器。 在舊終端中兩個輸出間仍有時間間隔。

運行完成後以下圖,注意兩個終端中的時間,服務器的響應是當即返回的。 

相關文章
相關標籤/搜索