西瓜皮

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

TP5任务队列使用Supervisor常驻进程

在使用 ThinkPHP5 的消息队列时,需要让 queue:work 进程常驻运行以持续处理任务。本文介绍如何使用 Supervisor 来管理这个进程。

一、环境说明

  • 操作系统:Linux
  • PHP 版本:7.x+
  • ThinkPHP 版本:5.x
  • 进程管理工具:Supervisor

二、安装 Supervisor

apt-get install supervisor
# 或
yum install supervisor

三、配置文件说明

1. 主配置文件:/etc/supervisord.conf

[supervisord]
http_port=/var/tmp/supervisor.sock ; HTTP监听端口,使用Unix域socket
;http_port=127.0.0.1:9001  ; 备用:使用TCP端口
;sockchmod=0700              ; Socket权限,AF_UNIX类型
;sockchown=nobody.nogroup     ; Socket所属用户和组
;umask=022                   ; 文件创建权限掩码
logfile=/var/log/supervisor/supervisord.log ; 主日志文件路径
logfile_maxbytes=50MB       ; 日志文件最大大小
logfile_backups=10          ; 日志文件保留备份数量
loglevel=info               ; 日志级别:debug,warn,info
pidfile=/var/run/supervisord.pid ; PID文件路径
nodaemon=false              ; 是否后台运行,false表示后台运行
minfds=1024                 ; 最小可用文件描述符
minprocs=200                ; 最小可用进程描述符

;nocleanup=true              ; 启动时是否清理临时文件
;http_username=user          ; HTTP认证用户名
;http_password=123           ; HTTP认证密码
;childlogdir=/tmp            ; 子进程日志目录
;user=chrism                 ; 运行Supervisor的用户
;directory=/tmp              ; 工作目录
;environment=KEY=value       ; 环境变量

[supervisorctl]
serverurl=unix:///var/tmp/supervisor.sock ; 连接Supervisor的socket地址
;serverurl=http://0.0.0.0:9001 ; 备用:使用TCP连接
;username=homexigua              ; CLI认证用户名
;password=              ; CLI认证密码
;prompt=mysupervisor         ; CLI提示符

[include]
files = /etc/supervisor/conf.d/*.conf ; 引入其他配置文件

2. 项目配置文件示例

[program:workJob]
command= /usr/local/bin/php think queue:work --queue workJob --daemon
directory=/www/wwwroot/your_project ; 项目根目录路径
;process_name=%(process_num)02d ; 进程名称模板
;numprocs=5 ; 启动进程数量
autostart=true ; 随Supervisor启动而自动启动
autorestart=true ; 进程异常退出后自动重启
startsecs=1 ; 进程启动后保持运行的最小秒数
startretries=5 ; 启动失败后的最大重试次数
redirect_stderr=true ; 将stderr重定向到stdout
stdout_logfile=/www/wwwroot/your_project/runtime/log/supervisor.log ; stdout日志路径

四、常见错误处理

错误:Another program is already listening...

Error: Another program is already listening on a port that one of our HTTP servers is configured to use. Shut this program down first before starting

解决方法:

rm -f /var/tmp/supervisor.sock
supervisord -c /etc/supervisord.conf

五、常用命令

# 启动Supervisor服务
supervisord -c /etc/supervisord.conf

# 启动所有进程
supervisorctl start all

# 查看进程状态
supervisorctl status

# 重启指定进程
supervisorctl restart workJob

# 停止所有进程
supervisorctl stop all

# 重载配置
supervisorctl reread
supervisorctl update

六、验证队列运行

1. 查看进程状态:

supervisorctl status

应该看到 workJob 状态为 RUNNING

2. 查看日志:

tail -f /www/wwwroot/your_project/runtime/log/supervisor.log

3. 测试队列任务:

向队列添加任务后,观察日志确认任务被正确消费处理。

七、总结

使用 Supervisor 管理 ThinkPHP5 队列进程,可以:

  • 保证进程异常退出后自动重启
  • 系统启动时自动运行
  • 统一管理多个队列进程
  • 方便查看运行状态和日志

建议定期检查日志文件大小,避免磁盘空间不足。

posted on 2018-02-28 14:43  西瓜皮  阅读(2828)  评论(0)    收藏  举报