简体   繁体   English

如何在PHP中同步侦听来自RabbitMQ队列的消息?

[英]How do you synchronously listen for messages from a RabbitMQ queue in PHP?

I am using RabbitMQ to implement a worker task queue for a search indexer process using the PHP AMQP extension . 我正在使用RabbitMQ使用PHP AMQP扩展为搜索索引器进程实现一个工作任务队列。 I need the search indexer demon to listen for messages on the queue and consume them when it's available. 我需要搜索索引器恶魔来侦听队列中的消息,并在它可用时使用它们。

I see two methods for consuming content from a queue: 我看到两种消耗队列内容的方法:

  • AMQPQueue::get - doesn't block, so probably not what I'm after AMQPQueue :: get - 不会阻止,所以可能不是我想要的
  • AMQPQueue::consume - seems promising AMQPQueue :: consume - 看起来很有希望

However, using consume appears to set up a consumer that is not then removed. 但是,使用消耗似乎会设置一个不会被删除的消费者。 Here's the PHP: 这是PHP:

$opts = array('min' => 1, 'max' => 10, 'ack' => false);
$messages = array();
while (count($messages) or $messages = $q->consume($opts)) {
    $msg = array_pop($messages);
    var_dump($msg);
    // ...Do work here...
    $q->ack($msg['delivery_tag']);
}

And you can see the consumers building up using rabbitmqctl: 您可以看到使用rabbitmqctl构建的消费者:

[andrew@localhost ~] rabbitmqctl list_queues name consumers
Listing queues ...
test_queue   3
[andrew@localhost ~] rabbitmqctl list_queues name consumers
Listing queues ...
test_queue   4

So the question is, what is the correct way to bind a PHP daemon to a queue such that it blocks while it waits for messages to be available, and starts blocking/listening again when it has completed the work associated with each message batch? 所以问题是,将PHP守护程序绑定到队列以使其在等待消息可用时阻塞的正确方法是什么,并在完成与每个消息批处理相关联的工作时再次开始阻塞/侦听?

I'm not sure how the PHP Pecl extension implements consumers, but my Amqp library allows you to listen out for incoming messages (ie consume) by calling a function, and there are several " exit strategies " available in case you don't want to block forever. 我不确定PHP Pecl扩展如何实现消费者,但是我的Amqp库允许你通过调用函数来监听传入消息(即消费),并且有几个“ 退出策略 ”可用,以防你不想要永远地阻止 There's documentation available here , check the section "Implementing a Consumer", and a demo script here. 这里有文档 ,请在此处查看“实现消费者”部分和演示脚本

consume is what you want. 消费是你想要的。 It'll block until it receives a message. 它会阻止,直到收到消息。

The API has changed a big since your code, so it's hard to guess what went wrong. 自您的代码以来,API已经发生了很大变化,所以很难猜出出了什么问题。

http://www.php.net/manual/en/amqpqueue.consume.php http://www.php.net/manual/en/amqpqueue.consume.php

has the semi latest documentation and example 有半最新的文档和示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM