2012-09-07 17 views
0

我擁有基於PHP的標準AMQP類的簡單隊列工作程序。它與RabbitMQ一起作爲服務器。我有用於初始化AMQP連接的隊列類,以及RabbitMQ。一切工作正常與下面的代碼:在PHP中使用進程分叉的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); 
     } 
    } 
    } 
} 

任何幫助將不勝感激......

回答

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