嗨大家好,我是Sean!
今天我們來完成Celery&Redis的搭檔合作!
首先,我們先來介紹Celery是甚麼!
celery是django中熱門的異步處理任務工具,不僅是可以高效的處理列隊問題,同時也可以處理周期性任務!
Celery的作業邏輯大概如下:
那麼,我們正式進入Celery+Redis的世界!
首先,我們當然需要先安裝個Celery的套件! 別忘了我們昨天的redis套件!
pip install celery
pip install django-redis
我們新增檔案,celery.py以及task.py兩個檔案,分別在專案資料夾,以及app資料夾中。
接著,我們寫celery.py裡的內容:
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_practice.settings')
app = Celery('django_practice')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
測試是否配置正常,能否開始工作,成功的話會是下面這樣:
可以看到我們得到的回覆是這樣:
-------------- celery@LAPTOP-GQ49VIN0 v5.0.5 (singularity)
--- ***** -----
-- ******* ---- Windows-10-10.0.19044-SP0 2022-10-14 23:46:30
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app: django_practice:0x2283833b9d0
- ** ---------- .> transport: redis://127.0.0.1:6379/0
- ** ---------- .> results: disabled://
- *** --- * --- .> concurrency: 8 (solo)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. django_practice.celery.debug_task
[2022-10-14 23:46:30,210: INFO/MainProcess] Connected to redis://127.0.0.1:6379/0
[2022-10-14 23:46:30,214: INFO/MainProcess] mingle: searching for neighbors
[2022-10-14 23:46:31,235: INFO/MainProcess] mingle: all alone
[2022-10-14 23:46:31,246: WARNING/MainProcess] C:\Users\sean8\miniconda3\envs\py38\lib\site-packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory
leak, never use this setting in production environments!
warnings.warn('''Using settings.DEBUG leads to a memory
[2022-10-14 23:46:31,247: INFO/MainProcess] celery@LAPTOP-GQ49VIN0 ready.
那麼,我們今天的文章就到此為止! 感謝大家的收看!
我是Sean,你各位海上的人,我們明天見!