0

PHPの標準AMQPクラスに基づく単純なキュー ワーカーがあります。サーバーとしてRabbitMQで動作します。RabbitMQ で AMQP 接続を初期化するための Queue クラスがあります。以下のコードですべて正常に動作します。

$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
     }
   }
 }

ただし、キューコマンドの実行をフォークしたかったのですが、この場合、キューは最初のコマンドで何度も無限になります。$queue->ack(); でメッセージを受信したことを RabbitMQ に確認できません。私の分岐バージョン (テストのために子を 1 つだけ簡略化) は次のようになります。

$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 に答える