请教下各位开发的队列是怎么做监听的?用while死循环吗?希望能出个简单的例子谢谢。现在卡在这一块了...
如果您需要即时所有的异步处理,那么只能用while 死循环一直监听
如果你允许有一定的延迟,那么,我有一个方法,您参考下:
首先写一个sync.sh ,shell文件内容如下:
#!/bin/sh Cur_Dir=$(cd `dirname $0`; pwd) while [ 1 ] do echo '########### fectch from remote [begin]...' $Cur_Dir/../../yii amqp/product/listen echo '########### fectch from remote [complete]...' echo '########### sleep 3 seconds...' sleep 3 echo '########### sleep 3 seconds complete...' done
这个shell的每一个shell会sleep 3秒 ,然后继续执行 amqp/product/listen ,下面是这个controller对应的代码:
amqp/product/listen
/** * 接收数据 */ public function actionListen() { $this->open(); $callback = function(AMQPMessage $message) { if ($this->handleMessage($message->body)) { $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']); } }; $this->channel->basic_qos(null, 1, null); $this->channel->basic_consume($this->queueName, '', false, false, false, false, $callback); while(count($this->channel->callbacks)) { $this->i++; $this->channel->wait(); // 一次更新5次,以免内存泄露 if($this->i >=5){ $this->close(); exit; } } }
也就是shell 的while循环 开启一个php的进程,进行mq监听,循环5次,然后退出这个循环。结束,sleep 3秒,然后shell又开启一个php进程
这样就会间断性的监听,节省一点。
@Terry #1楼 非常感谢!!