Search code examples
javaqueuerabbitmqconsumerproducer

RabbitMQ: Routing key + queue + delay


I have a Producer as follows:

public class MyProducer {

private static final String EXCHANGE_NAME = "messages";

public static void main(String[] argv)
              throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    String color1 = "red"
    String message1 = "message1"

    String color2 = "blue"
    String message2 = "message2"

    channel.basicPublish(EXCHANGE_NAME, color1, null, message1);
    channel.basicPublish(EXCHANGE_NAME, color2, null, message2);

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

and also a consumer:

public class MyConsumer {

private static final String EXCHANGE_NAME = "messages";

public static void main(String[] argv)
              throws java.io.IOException,
              java.lang.InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    String queueName = channel.queueDeclare().getQueue();


    channel.queueBind(queueName, EXCHANGE_NAME, "color1");
    channel.queueBind(queueName, EXCHANGE_NAME, "color2");


    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);

}

}

My questions are now:

  1. Do I have now only one queue named "queuName" or do I have two queues named "color1" and "color2"?
  2. I don't want to consume the messages immediatly. So what I want is to set a delay for each queue "color1" and "color2". How can I achieve this?

Solution

  • Question-1) Do I have now only one queue named "queuName" or do I have two queues named "color1" and "color2"?

    Answer : You have to must go through tutorial

    https://www.rabbitmq.com/getstarted.html

    base on that you decide how you want to create queue and which exchange types[direct, topic, headers and fanout] match to your requirement or sometime its happen no need to exchange ..so first see tutorial and then base on your requirement decide.

    Question-2)I don't want to consume the messages immediately. So what I want is to set a delay for each queue "color1" and "color2". How can I achieve this?

    Answer: for that you have to write your own logic which delay the consumer to find message from rabbit, you can go through thread also.

    Enjoy Rabbit programming :)