How to create multiple queues based on routing keys in rabbitmq

    By: Manu
    5 months ago

    Here is the code example using php how you can use multiple queues based on routing key and process data as you like.


    global $connection;
    require 'connection.php';
    
    
    $channel = new AMQPChannel($connection);
    
    
    // Create a new queue with a different name
    $queue1 = new AMQPQueue($channel);
    $queue1->setName('my_Custom_Queue_1');
    $queue1->bind('Test1', 'routing_key_A');
    
    
    // Create another new queue with a different name and a different routing key
    $queue2 = new AMQPQueue($channel);
    $queue2->setName('my_Custom_Queue_2');
    $queue2->bind('Test1', 'routing_key_B');
    
    
    while (true) {
        $message1 = $queue1->get();
        $message2 = $queue2->get();
    
    
        if ($message1) {
            echo "Received in Queue 1: " . $message1->getBody() . "\n";
            // Acknowledge the message after processing
            $queue1->ack($message1->getDeliveryTag());
        }
    
    
        if ($message2) {
            echo "Received in Queue 2: " . $message2->getBody() . "\n";
            // Acknowledge the message after processing
            $queue2->ack($message2->getDeliveryTag());
        }
    }
    


    Watch carefully as we are using 2 routing keys passing single exchange name. Also we create 2 instances for $queue1 and $queue2.


    So this works flawlessly otherwise it could be this way if it was on single queue based system.


    <?php
    global $connection;
    require 'connection.php';
    
    $channel = new AMQPChannel($connection);
    $queue = new AMQPQueue($channel);
    $queue->setName('my_Custom_Queue');
    $queue->bind('Test1', 'routing_key_A');
    $queue->bind('Test1', 'routing_key_B');
    
    while (true) {
        $message = $queue->get();
    
        if ($message) {
            echo "Received: " . $message->getBody() . "\n";
    
    
            // Acknowledge the message after processing
            $queue->ack($message->getDeliveryTag());
        }
    
    }