drcmg28484 2012-09-07 10:50
浏览 65
已采纳

Rabbitmq队列与PHP中的进程分叉

I have simple queue worker based on standard AMQP Class from PHP. It works with RabbitMQ as a server. I have Queue Class for initialize AMQP connection wirh RabbitMQ. Everything works fine with code below:

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

However I wanted to fork queue command execution, but in this case queue goes endless with the first command over and over again. I can't acknowledge RabbitMQ that message was recieved with $queue->ack(); My forked version (simplified with only one child for testing sake) looks like this :

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

any help will be appreciated...

  • 写回答

1条回答 默认 最新

  • du9698 2012-09-07 11:56
    关注

    I finally solved the problem! I had to run ack command from child process, it works this way! This is correct code:

    $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);
          }
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题