PHP Amqp channel callback loop

梦想的初衷 提交于 2019-12-11 04:38:36

问题


The example code for RabbitMQ states

Our code will block while our $channel has callbacks. Whenever we receive a message our $callback function will be passed the received message.

With this code snippet

while(count($channel->callbacks)) {
    $channel->wait();
}

This confuses me, because the default timeout for PhpAmqpLib\Channel\AbstractChannel::wait is forever.

public function wait($allowed_methods = null, $non_blocking = false, $timeout = 0)

So if wait blocks forever, how would the code ever reach a second iteration of the while loop?

Would it be safe to say the while loop is only necessary if wait is passed a $timeout > 0?


回答1:


The timeout parameter on the wait call is how long to wait for the next message before giving up. The default value, as you say, is "forever", which means "until a message arrives".

However, once a single message has been received and processed, the wait call exits; it could perhaps be named waitForNextEvent(). You can see that in the source you linked to:

if ($this->should_dispatch_method($allowed_methods, $method_sig)) {
    return $this->dispatch($method_sig, $args, $amqpMessage);
}

So to receive more than one message, you need to call wait() more than once. Generally, in a consumer, you want to call it an infinite number of times, so you could just use while(true), but allowing the loop to exit if you unregister all your callbacks gives you a way of gracefully exiting.




回答2:


the code you are showing, would represent the worker or processor of the AMQP messages

Because it will listen for dropped messages from the AMQP server, it will be waiting/listening/looping forever for these messages.



来源:https://stackoverflow.com/questions/42933465/php-amqp-channel-callback-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!