J
J
John Doe2017-09-18 03:29:19
PHP
John Doe, 2017-09-18 03:29:19

How to return a task to the queue in RabbitMQ and PHP?

How can I return the message back to the queue if the processing result did not suit me. I found only information about message acknowledgments , but I think that this does not suit me. It is necessary for me that if as a result of processing I receive the RETRY parameter, the message is added to the queue. And then this worker or another picks it up again and tries to process it.
For example like this:

<?php
use PhpAmqpLib\Connection\AMQPStreamConnection;

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$connection = new AMQPStreamConnection($AMQP);
$channel = $connection->channel();

$channel->queue_declare('test', false, false, false, false);

$callback = function($msg) {
  $condition = json_decode($msg->body);

  if (!$condition) {
    # return to the queue
  }
};

$channel->basic_consume('test', '', false, true, false, false, $callback);

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

$channel->close();
$connection->close();
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
John Doe, 2017-09-18
@rabbit418

The solution turned out to be simpler than I thought, it turns out that the task was not about RabbitMQ specifically, but about the scope of variables. If anyone is interested in the solution, here it is:

<?php
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$connection = new AMQPStreamConnection($AMQP);
$channel = $connection->channel();

$channel->queue_declare('test', false, false, false, false);

$callback = function($msg) {
  global $channel;

  $condition = json_decode($msg->body);

  if (!$condition) {
    $msg = new AMQPMessage(json_encode(array(
      'condition' => false
    )));

    $channel->basic_publish($msg, '', 'test');
  }
};

$channel->basic_consume('test', '', false, true, false, false, $callback);

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

$channel->close();
$connection->close();
?>

M
My joy, 2017-11-17
@t-alexashka

$callback = function($msg) {
    global $channel;

also possible like this:
$callback = function($msg) use ($channel) {
    ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question