title: php rabbitmq consumer reconnect
body: <p>I have a PHP app that uses RabbitMQ.   For redundancy, I created a pair of RabbitMQ servers and joined them in a cluster.  I also have a VyOS failover cluster running HAProxy to load balance connections and to provide rerouting in case of a failover.</p>
  
  <p>Yesterday, our VyOS cluster decided a failover was needed (probably a brief network interruption).  HAproxy was stopped on one VyOS the virtual IP's moved, and restarted HAproxy on the other node.</p>
  
  <p>After this, I viewed the queues in Rabbit and saw there was zero consumers for each queue.  I checked the machines running the consumers still had the PHP running.   I left them for a while to see if they'd reconnect and they did not.  I had to kill the PHP script and restart them, and they re-connected and began consuming immediately.</p>
  
  <p>I think that RabbitMQ and HAproxy are working as expected... Now I need the PHP consumer to support a failover event... in otherwords, instead of just hanging, it needs to detect a disconnection, and automatically reconnect.</p>
  
  <p>Here is my RabbitMQ class.  Thanks for any help in advance!</p>
  
  <pre><code>&lt;?php
  while(true)
  {
      try{getMessages("transcode2");}
      catch(Exception $e){echo($e-&gt;getMessage()."\n");}
      sleep(1);
  }
  require_once("../api/db.php");
  require_once("../vendor/autoload.php");
  use PhpAmqpLib\Connection\AMQPStreamConnection;
  use PhpAmqpLib\Message\AMQPMessage;
  function sendMessage($msg,$prio)
  {
      global $channel;
      $msg=json_encode($msg);
      $queue="transcode2";
      $channel-&gt;queue_declare($queue,true,false,false,false);
      $channel-&gt;basic_publish(new AMQPMessage($msg,array('priority' =&gt; $prio)),'',$queue);
  }
  function getMessages($queue)
  {
      global $connection,$channel;
      $connection=new AMQPStreamConnection(RABBITMQ_SERVER,RABBITMQ_PORT,RABBITMQ_USERNAME,RABBITMQ_PASSWORD);
      $channel=$connection-&gt;channel();
      $channel-&gt;queue_declare($queue,true,false,false,false);
      $callback=function($msg)
      {
          if(handleMessage(json_decode($msg-&gt;body,true)))
          {
              $msg-&gt;delivery_info['channel']-&gt;basic_ack($msg-&gt;delivery_info['delivery_tag']);
          }
          else
          {
              $msg-&gt;delivery_info['channel']-&gt;basic_nack($msg-&gt;delivery_info['delivery_tag'],false,true);
          }
      };
      $channel-&gt;basic_qos(null,1,null);
      $channel-&gt;basic_consume($queue,'',false,false,false,false,$callback);
      while(count($channel-&gt;callbacks))
      {
          try{$channel-&gt;wait();}
          catch(Exception $e)
          {
              break;
          }
      }
      $channel-&gt;close();
      $connection-&gt;close();
  }
  ?&gt;
  </code></pre>