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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器