Search code examples
phpamqpphp-amqplib

PHP AMQP pass headers in request


I am trying to send a request to AMQP, stuck at how to add header to the request message, the below is the wrapper we are having

$message = ‘{"empId": ‘.$empId.', “empName”:”my name"}’;
 $resData = $rpcClient->call($message, self::EXCHANGE, self::ROUTING_KEY);

How to add headers to the above message

the call method is the wrapper we have written

public function call($requestMessage, $exchange, $routingKey)
{
    $this->response = null;
    $this->correlationId = uniqid('abcprod', true);

    $message = new AMQPMessage(
        strval($requestMessage),
        array('correlation_id' => $this->correlationId, 'reply_to' => $this->callbackQueue)
    );

    $this->channel
        ->basic_publish($message, $exchange, $routingKey);

    try {
        $this->channel->wait(null, false, self::REQUEST_TIMEOUT);
    } catch (AMQPTimeoutException $e) {
        return null;
    }

    return $this->response;
}

Solution

  • When you create the message, you should set the application_headers property. This should be a Wire\AMQPTable that takes as a constructor argument an array of headers.

    The official amqp_message_headers_snd.php example:

    $message = new AMQPMessage($data);
    
    $headers = new Wire\AMQPTable(array(
       'x-foo'=>'bar',
       'table'=>array('figuf', 'ghf'=>5, 5=>675),
       'num1' => -4294967295,
       'num2' => 5,
       'num3' => -2147483648,
       'true' => true,
       'false' => false,
       'void' => null,
       'date' => new DateTime(),
       'array' => array(null, 'foo', 'bar', 5, 5674625, 'ttt', array(5, 8, 2)),
       'arr_with_tbl' => array(
          'bar',
          5,
          array('foo', 57, 'ee', array('foo'=>'bar', 'baz'=>'boo', 'arr'=>array(1,2,3, true, new DateTime()))),
          67,
          array(
             'foo'=>'bar',
             5=>7,
             8=>'boo',
             'baz'=>3
          )
       ),
       '64bitint' => 9223372036854775807,
       '64bit_uint' => '18446744073709600000',
       '64bitint_neg' => -pow(2, 40)
    ));
    $headers->set('shortshort', -5, Wire\AMQPTable::T_INT_SHORTSHORT);
    $headers->set('short', -1024, Wire\AMQPTable::T_INT_SHORT);
    
    $message->set('application_headers', $headers);