python 關於celery的異步任務隊列的基本使用(celery+redis)【采用配置文件設置】


工程結構說明:源文件下載請訪問https://i.cnblogs.com/Files.aspx

__init__.py:實例化celery,並加載配置模塊

celeryconfig.py:配置模塊

task1:任務1,實現加法

task2:任務2,實現乘法

app.py:應用,任務生產者

 

1、__init__.py:實例化celery,並加載配置模塊

# -*- coding: utf-8 -*-

from celery import Celery

myapp=Celery('demo')

#通過Celery實例加載配置模塊celeryconfig.py
myapp.config_from_object('celerywithconfig.celeryconfig') 

 

 2、celeryconfig.py:配置模塊

# -*- coding: utf-8 -*-

'''
Created on 2019年8月28日

@author: lenovo
'''
BROKER_URL='redis://localhost:6379/1'

CELERY_RESULT_BACKEND='redis://localhost:6379/2'

CELERY_TIMEZONE='Asia/Shanghai'#不指定時區的話默認采用UTC

#導入指定的任務模塊
CELERY_IMPORTS=(
    'celerywithconfig.task1',
    'celerywithconfig.task2',
    )

 

3、task1:任務1,實現加法

# -*- coding: utf-8 -*-

'''
Created on 2019年8月28日

@author: lenovo
'''
import time

#從__init__.py中導入實例化的Celery myapp
from celerywithconfig import myapp

@myapp.task
def add(x,y):
    time.sleep(3)
    return x+y

 

4、task2:任務2,實現乘法

# -*- coding: utf-8 -*-

'''
Created on 2019年8月28日

@author: lenovo
'''
import time
from celerywithconfig import myapp

@myapp.task
def multiply(x,y):  
    time.sleep(4)
    return x * y

 

5、app.py:應用,任務生產者

# -*- coding: utf-8 -*-

'''
Created on 2019年8月28日

@author: lenovo
'''
from celerywithconfig import task1
from celerywithconfig import task2

task1.add.delay(2, 4)
task2.multiply.delay(4, 5)
print 'end...'

 

6、啟動worker,監聽任務

cd到src路徑下,執行命令python -m celery -A celerywithconfig worker --loglevel=info

 

7、執行app.py,生產任務

8、查看任務消費情況:worker日志顯示同時接收到了2個任務,並分別進行了消費:

9、查看任務消費情況:消費結果成功保存在backend中: 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM