Laravel官網教程中,並沒有提到用它來寫CLI應用,即守護進程或者可執行腳本。但是它卻提供了更加便捷的隊列(Queue)功能。
Laravel隊列
我們在開發應用過程中難免會遇到處理耗時任務的需求,這些任務如果直接在用戶的請求中處理,必然會導致頁面顯示被阻塞。雖然利用fastcgi的一些特性可以先輸出頁面,后台任務繼續執行,但是這樣遠遠不如將任務交給異步隊列來處理方便。
配置和啟動
Laravel隊列功能為我們提供了一個便捷的方式去處理這些異步任務,配置一個隊列只需要以下幾步:
- 配置
app/config/queue.php中的default配置項為系統中的隊列系統,sync是直接執行,並不是異步隊列。 - 創建隊列處理類,如
SendMail。類文件位置可以參考我的另一篇文章在Laravel中使用自己的類庫三種方式 - 將應用中的一個任務推送到隊列
Queue::push('SendMail') - 啟動Laravel隊列監聽器
php artisan queue:listen或者用php artisan queue:work處理隊頭的一條消息
Laravel隊列並行處理
如果使用過Laravel隊列的朋友應該發現,queue:listen是線性執行的,即一個任務做完以后才會讀取下一條任務。這樣並不能滿足我們日常的異步耗時任務處理的需求,於是有人建議啟動多個queue:listen。
php artisan queue:listen && php artisan queue:listen ...
這樣雖然理論上是可行的,因為在異步隊列的幫助下,程序並不會出現沖突。但是由於PHP本身對內存處理的缺陷,很難保證一個長期運行在后台的程序不出現內存泄露,例如queue:listen這樣的死循環程序。因此在正式環境中我們更傾向於使用多個queue:work並行執行異步隊列中的任務。queue:work只是讀取隊首的一項任務,執行完成后即結束程序,如果沒有任務也會結束程序。這個方式類似於PHP對於WEB請求的處理,不會出現內存泄露。
利用Supervisor可以便捷的創建基於queue:work的異步隊列並行處理。
Supervisor
Supervisor是一個進程控制系統,由python編寫,它提供了大量的功能來實現對進程的管理。
- 程序的多進程啟動,可以配置同時啟動的進程數,而不需要一個個啟動
- 程序的退出碼,可以根據程序的退出碼來判斷是否需要自動重啟
- 程序所產生日志的處理
- 進程初始化的環境,包括目錄,用戶,umask,關閉進程所需要的信號等等
- 手動管理進程(開始,啟動,重啟,查看進程狀態)的web界面,和xmlrpc接口
安裝
pip install supervisor
配置
配置項示例如下,后面我們會詳細創建一個獨有的Laravel配置
; Sample supervisor config file.
;
; For more information on the config file, please see:
; http://supervisord.org/configuration.html
;
; Note: shell expansion ("~" or "$HOME") is not supported. Environment
; variables can be expanded using this syntax: "%(ENV_HOME)s".
[unix_http_server] ; supervisord的unix socket服務配置
file=/tmp/supervisor.sock ; socket文件的保存目錄
;chmod=0700 ; socket的文件權限 (default 0700)
;chown=nobody:nogroup ; socket的擁有者和組名
;username=user ; 默認不需要登陸用戶 (open server)
;password=123 ; 默認不需要登陸密碼 (open server)
;[inet_http_server] ; supervisord的tcp服務配置
;port=127.0.0.1:9001 ; tcp端口
;username=user ; tcp登陸用戶
;password=123 ; tcp登陸密碼
[supervisord] ; supervisord的主進程配置
logfile=/tmp/supervisord.log ; 主要的進程日志配置
logfile_maxbytes=50MB ; 最大日志體積,默認50MB
logfile_backups=10 ; 日志文件備份數目,默認10
loglevel=info ; 日志級別,默認info; 還有:debug,warn,trace
pidfile=/tmp/supervisord.pid ; supervisord的pidfile文件
nodaemon=false ; 是否以守護進程的方式啟動
minfds=1024 ; 最小的有效文件描述符,默認1024
minprocs=200 ; 最小的有效進程描述符,默認200
;umask=022 ; 進程文件的umask,默認200
;user=chrism ; 默認為當前用戶,如果為root則必填
;identifier=supervisor ; supervisord的表示符, 默認時'supervisor'
;directory=/tmp ; 默認不cd到當前目錄
;nocleanup=true ; 不在啟動的時候清除臨時文件,默認false
;childlogdir=/tmp ; ('AUTO' child log dir, default $TEMP)
;environment=KEY=value ; 初始鍵值對傳遞給進程
;strip_ansi=false ; (strip ansi escape codes in logs; def. false)
; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket
;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket
;username=chris ; 如果設置應該與http_username相同
;password=123 ; 如果設置應該與http_password相同
;prompt=mysupervisor ; 命令行提示符,默認"supervisor"
;history_file=~/.sc_history ; 命令行歷史紀錄
; The below sample program section shows all possible program subsection values,
; create one or more 'real' program: sections to be able to control them under
; supervisor.
;[program:theprogramname]
;command=/bin/cat ; 運行的程序 (相對使用PATH路徑, 可以使用參數)
;process_name=%(program_name)s ; 進程名表達式,默認為%(program_name)s
;numprocs=1 ; 默認啟動的進程數目,默認為1
;directory=/tmp ; 在運行前cwd到指定的目錄,默認不執行cmd
;umask=022 ; 進程umask,默認None
;priority=999 ; 程序運行的優先級,默認999
;autostart=true ; 默認隨supervisord自動啟動,默認true
;autorestart=unexpected ; whether/when to restart (default: unexpected)
;startsecs=1 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; 期望的退出碼,默認0,2
;stopsignal=QUIT ; 殺死進程的信號,默認TERM
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false ; 向unix進程組發送停止信號,默認false
;killasgroup=false ; 向unix進程組發送SIGKILL信號,默認false
;user=chrism ; 為運行程序的unix帳號設置setuid
;redirect_stderr=true ; 將標准錯誤重定向到標准輸出,默認false
;stdout_logfile=/a/path ; 標准輸出的文件路徑NONE=none;默認AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_capture_maxbytes=1MB ; number of bytes in 'capturemode' (default 0)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10 ; # of stderr logfile backups (default 10)
;stderr_capture_maxbytes=1MB ; number of bytes in 'capturemode' (default 0)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A=1,B=2 ; process environment additions (def no adds)
;serverurl=AUTO ; override serverurl computation (childutils)
; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more 'real'
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.
;[eventlistener:theeventlistenername]
;command=/bin/eventlistener ; 運行的程序 (相對使用PATH路徑, 可以使用參數)
;process_name=%(program_name)s ; 進程名表達式,默認為%(program_name)s
;numprocs=1 ; 默認啟動的進程數目,默認為1
;events=EVENT ; event notif. types to subscribe to (req'd)
;buffer_size=10 ; 事件緩沖區隊列大小,默認10
;directory=/tmp ; 在運行前cwd到指定的目錄,默認不執行cmd
;umask=022 ; 進程umask,默認None
;priority=-1 ; 程序運行的優先級,默認-1
;autostart=true ; 默認隨supervisord自動啟動,默認true
;autorestart=unexpected ; whether/when to restart (default: unexpected)
;startsecs=1 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; 期望的退出碼,默認0,2
;stopsignal=QUIT ; 殺死進程的信號,默認TERM
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false ; 向unix進程組發送停止信號,默認false
;killasgroup=false ; 向unix進程組發送SIGKILL信號,默認false
;user=chrism ; setuid to this UNIX account to run the program
;redirect_stderr=true ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups ; # of stderr logfile backups (default 10)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A=1,B=2 ; process environment additions
;serverurl=AUTO ; override serverurl computation (childutils)
; The below sample group section shows all possible group values,
; create one or more 'real' group: sections to create "heterogeneous"
; process groups.
;[group:thegroupname]
;programs=progname1,progname2 ; 任何在[program:x]中定義的x
;priority=999 ; 程序運行的優先級,默認999
; The [include] section can just contain the "files" setting. This
; setting can list multiple files (separated by whitespace or
; newlines). It can also contain wildcards. The filenames are
; interpreted as relative to this file. Included files *cannot*
; include files themselves.
;[include]
;files = relative/directory/*.ini
Laravel配置
在supervisor的include中,我們可以創建一個SendMail項目
[program:waaQueue]
command = php artisan queue:work
directory = /path/to/app
process_name = %(program_name)s_%(process_num)s
numprocs = 6
autostart = true
autorestart = true
stdout_logfile = /path/to/app/storage/logs/supervisor_waaQueue.log
stdout_logfile_maxbytes = 10MB
stderr_logfile = /path/to/app/storage/logs/supervisor_wqqQueue.log
stderr_logfile_maxbytes = 10MB
啟動
- 首先啟動supervisord,執行
supervisord即可,它會在默認目錄下尋找配置文件 - 運行
supervisorctl help來查看可使用命令
轉載:http://yansu.org/2014/03/22/managing-your-larrvel-queue-by-supervisor.html
