Super Saver Flight Deals - 468x60banner

Reply To: RabbitMQ – How to get messages with certain routing keys?

#3174 Reply

Jonathan65

This is the code :

String myMessage;
String routingKeyReceived;

private void getMessage() {
String FROM_QUEUE_NAME = “FromQueue”;
String EXCHANGE_NAME = “amq.topic”;
myMessage = “”;
routingKeyReceived = “”;

ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("test");
factory.setPassword("test");
factory.setVirtualHost("MyVirtualHost");
factory.setHost("172...");
factory.setPort(5672);

try 
{
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);

    channel.queueDeclare(FROM_QUEUE_NAME, true, false, false, null);

    channel.queueBind(FROM_QUEUE_NAME, EXCHANGE_NAME, "MyRouting.Route.RtKey1");
    channel.queueBind(FROM_QUEUE_NAME, EXCHANGE_NAME, "MyRouting.Route.RtKey2");

    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        myMessage = new String(delivery.getBody(), "UTF-8");
        routingKeyReceived = delivery.getEnvelope().getRoutingKey();
    };
    channel.basicConsume(FROM_QUEUE_NAME, true, deliverCallback, consumerTag -> { });

    channel.close();
    connection.close();

} catch (Exception e) {
}

}
<Strong/>