RabbitMQ - Create Queue using queueDeclare in Java

by
Jeremy Canfield |
Updated: July 28 2022
| RabbitMQ articles
The queue.declare method can be used to create a RabbitMQ queue. In this example, a queue named foo should be created. The comma sepearate fields are:
- Queue Name
- Durable (true or false)
- Exclusive (true or false)
- autoDelete the queue (true or false)
- arguments
package com.rabbitmq.demo;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.text.*;
public class declare {
public void amqDeclare() throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException {
ConnectionFactory cf = new ConnectionFactory();
String vhost = "bar";
cf.setUri("amqps://john.doe:itsasecret@server1.example.com:5671/" + vhost);
Connection conn = null;
try {
conn = cf.newConnection();
if (conn != null) {
System.out.println("Successfully connected to " + conn);
}
else {
System.out.println("Failed to connect to " + conn);
}
Channel channel = conn.createChannel();
String queueName = "foo";
boolean mandatory = true;
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("MM/dd/yyyy 'at' hh:mm:ss a");
channel.queueDeclare(queueName, true, true, true);
System.out.println("Successfully created queue " + queueName + " on virtual host " + vhost + " on " + ft.format(date));
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
System.out.println("Successfully closed the connection to " + conn);
}
}
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at