Skip to content

Commit fcee9a0

Browse files
committed
[amqp-ext] Add basic consume method.
1 parent d401385 commit fcee9a0

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

‎pkg/amqp-ext/AmqpConsumer.php‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,52 @@ public function reject(PsrMessage $message, $requeue = false)
188188
);
189189
}
190190

191+
/**
192+
* @param float|int $timeout milliseconds, consumes endlessly if zero set
193+
* @param callable $callback A callback function to which the
194+
* consumed message will be passed. The
195+
* function must accept at a minimum
196+
* one parameter, an \Interop\Amqp\AmqpMessage object,
197+
* and an optional second parameter
198+
* the \Interop\Amqp\AmqpConsumer from which the message was
199+
* consumed. The \Interop\Amqp\AmqpConsumer::consume() will
200+
* not return the processing thread back to
201+
* the PHP script until the callback
202+
* function returns FALSE.
203+
*/
204+
public function basicConsume($timeout, callable $callback = null)
205+
{
206+
/** @var \AMQPQueue $extQueue */
207+
$extConnection = $this->getExtQueue()->getChannel()->getConnection();
208+
209+
$originalTimeout = $extConnection->getReadTimeout();
210+
try {
211+
$extConnection->setReadTimeout($timeout / 1000);
212+
213+
if ($callback) {
214+
$this->getExtQueue()->consume(function (\AMQPEnvelope $extEnvelope, \AMQPQueue $q) use (&$callback) {
215+
$message = $this->convertMessage($extEnvelope);
216+
$message->setConsumerTag($q->getConsumerTag());
217+
218+
$queue = $this->context->createQueue($q->getName());
219+
$consumer = $this->context->createConsumer($queue);
220+
221+
return call_user_func($callback, $message, $consumer);
222+
}, AMQP_JUST_CONSUME);
223+
} else {
224+
$this->getExtQueue()->consume(null, Flags::convertConsumerFlags($this->flags), $this->consumerTag);
225+
}
226+
} catch (\AMQPQueueException $e) {
227+
if ('Consumer timeout exceed' == $e->getMessage()) {
228+
return null;
229+
}
230+
231+
throw $e;
232+
} finally {
233+
$extConnection->setReadTimeout($originalTimeout);
234+
}
235+
}
236+
191237
/**
192238
* @param int $timeout
193239
*

0 commit comments

Comments
 (0)