Is there a way to consume messages from RabbitMQ exchange ( not to produce messages)

43 Views Asked by At

I am developing a consumer for a third party RabbitMQ broker over AMQP 1.0 protocol. Where I am unable to consume messages for the reason that this Third party asks us to consume messages by connecting to a RabbitMQ exchange. Where as I understand that an exchange is for producing but not for consuming messages.

the third party is insisting on consumption from exchange and has not provided any queue name. Please help me If my understanding is wrong and provide any references to library that can support me.

Solution Design.

  1. Protocol: AMQP 1.0
  2. Client Library: Apache ProtonJ2
  3. Broker Product: RabbitMQ
  4. Programing Language: Java 17

The ICD provides following insights,

  1. Exchange:- The exchange is not bind to any queue
  2. Producer:- Producer is sending messages but these are getting discarded for the reason that exchange is bot bind to any queue.
  3. Consumer:- as soon as the consumer connects to the exchange, RabbitMQ creates a server named queue and binds it to the exchange.
  4. Consumer:- Consumer starts receiving messages from the exchange as the bound queue contains the messages. Please not that consumer has not created any connection to this server named queue. Consumer shall only connect to exhcnage

Please help me in proton library example to do this.

1

There are 1 best solutions below

2
ru4ert On BEST ANSWER

Since you didn't provide more informations to your code i would answer with a basic consumer boilerplate:

import org.apache.qpid.protonj2.client.*;
import org.apache.qpid.protonj2.client.exceptions.ClientException;

public class RabbitMQConsumer {
    public static void main(String[] args) {
        String brokerUrl = "amqp://your.rabbitmq.server:port";
        String exchangeName = "yourExchangeName";

        try {
            Client client = Client.create();
            Connection connection = client.connect(brokerUrl);
            Session session = connection.openSession();

            // Assuming RabbitMQ creates a server-named queue and binds it when the consumer connects
            Receiver receiver = session.openReceiver(exchangeName);

            receiver.handler((delivery, message) -> {
                String body = message.getBody().toString();
                // Process message
                System.out.println("Received message: " + body);
            });

            receiver.open();
            System.out.println("Connected to exchange and waiting for messages...");

            // Keep the application running to listen for messages
            Thread.currentThread().join();
        } catch (ClientException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}