predis 配合 supervisord 做消息队列
不是完整的代码,了解大概用。我的测试服务器比较老。centos 6.5
yum install supervisord // 直接安装
安装解释后,配置/监听可执行文件 /etc/supervisord.conf
[program:predis_program] command=/usr/bin/php /www/web/queue/index.php autostart=true autorestart=true user=web redirect_stderr=true stdout_logfile=/var/log/predis.log
直接启动
service supervisord start // 启动
index.php中,使用了 predis库,show code
require "./library/predis/vendor/autoload.php"; Predis\Autoloader::register(); // 定义远程接口地址和其他参数 $remoteApi = 'https://www.ab.com/api'; // 实例化 Redis $client = new Predis\Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); // 定义处理函数 function handleQueueItem($item, $remoteApi) { // 将消息队列中的数据解析为数组或对象 $data = json_decode($item, true); // 向远程接口发送请求 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $remoteApi); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $response = curl_exec($ch); curl_close($ch); // 处理远程接口返回的数据 // ... } // 开始监听消息队列 while (true) { // 从队列中获取数据 $item = $client->lpop('message_queue'); if ($item) { // 处理队列中的数据 handleQueueItem($item, $remoteApi); } // 休眠 1 秒 sleep(1); }
代码结束。
系统设置自启动 Centos 6.5
添加 启动配置文件 /etc/init.d/supervisord
#!/bin/bash # # supervisord Startup script for the Supervisor process control system # # chkconfig: - 95 04 # description: Supervisor is a client/server system that allows its users \ # to monitor and control a number of processes on UNIX-like \ # operating systems. # processname: supervisord # config: /etc/supervisord.conf # pidfile: /var/run/supervisord.pid # Source function library . /etc/rc.d/init.d/functions # Source system settings if [ -f /etc/sysconfig/supervisord ]; then . /etc/sysconfig/supervisord fi prog="supervisord" pidfile=${PIDFILE-/var/run/$prog.pid} lockfile=${LOCKFILE-/var/lock/subsys/$prog} start() { echo -n $"Starting $prog: " daemon --pidfile=${pidfile} supervisord -c /etc/supervisord.conf RETVAL=$? echo [ $RETVAL -eq 0 ] && touch ${lockfile} return $RETVAL } stop() { echo -n $"Stopping $prog: " killproc -p ${pidfile} ${prog} RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f ${lockfile} ${pidfile} } reload() { echo -n $"Reloading $prog: " killproc -p ${pidfile} ${prog} -HUP RETVAL=$? echo } case "$1" in start) start ;; stop) stop ;; status) status -p ${pidfile} ${prog} RETVAL=$? ;; restart) stop start ;; condrestart) if [ -f ${pidfile} ] ; then stop start fi ;; reload) reload ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}" RETVAL=2 ;; esac exit $RETVAL
授权
chmod +x /etc/init.d/supervisord
添加到系统服务并设置为开机自启
chkconfig --add supervisord chkconfig supervisord on