0

我有基于PHP标准AMQP类的简单队列工作者。它与 RabbitMQ 作为服务器一起使用。我有用于初始化 AMQP 连接 wirh RabbitMQ 的队列类。下面的代码一切正常:

$queue = new Queue('myQueue');

 while($envelope = $queue->getEnvelope()) {
   $command = unserialize($envelope->getBody());

   if ($command instanceof QueueCommand) {
     try {
       if ($command->execute()) {
         $queue->ack($envelope->getDeliveryTag());
       }
     } catch (Exception $exc) {
       // an error occurred so do some processing to deal with it
     }
   }
 }

但是我想分叉队列命令执行,但在这种情况下,队列会一遍又一遍地与第一个命令一起执行。我无法确认 RabbitMQ 收到的消息是 $queue->ack(); 我的分叉版本(为了测试而简化了只有一个孩子)看起来像这样:

$queue = new Queue('myQueue');

while($envelope = $queue->getEnvelope()) {
  $command = unserialize($envelope->getBody());

  if ($command instanceof QueueCommand) {
    $pid = pcntl_fork();

    if ($pid) {
      //parent proces
      //wait for child
      pcntl_waitpid($pid, $status, WUNTRACED);

      if($status > 0) {
        // an error occurred so do some processing to deal with it
      } else {
        //remove Command from queue
        $queue->ack($envelope->getDeliveryTag());
      }
    } else {
      //child process
      try {
        if ($command->execute()) {
          exit(0);
        }
      } catch (Exception $exc) {
        exit(1);
      }
    }
  }
}

任何帮助将不胜感激...

4

1 回答 1

2

我终于解决了问题!我必须从子进程运行 ack 命令,它是这样工作的!这是正确的代码:

$queue = new Queue('myQueue');

while($envelope = $queue->getEnvelope()) {
  $command = unserialize($envelope->getBody());

  if ($command instanceof QueueCommand) {
    $pid = pcntl_fork();

    if ($pid) {
      //parent proces
      //wit for child
      pcntl_waitpid($pid, $status, WUNTRACED);

      if($status > 0) {
        // an error occurred so do some processing to deal with it
      } else {
        // sucess
      }
    } else {
      //child process
      try {
        if ($command->execute()) {
          $queue->ack($envelope->getDeliveryTag());
          exit(0);
        }
      } catch (Exception $exc) {
        exit(1);
      }
    }
  }
}
于 2012-09-07T11:56:10.610 回答