Skip to content

Instantly share code, notes, and snippets.

@kirshiyin89
Created September 1, 2020 21:44
Show Gist options
  • Save kirshiyin89/d6e20c4e45e4e8429f99910c53cfca4b to your computer and use it in GitHub Desktop.
Save kirshiyin89/d6e20c4e45e4e8429f99910c53cfca4b to your computer and use it in GitHub Desktop.
Create RabbitMQ connection
private Connection createConnection() throws TimeoutException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
// "guest"/"guest" by default, limited to localhost connections
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
factory.setHost("127.0.0.1");
factory.setPort(5672);
return connectToRabbitMQ(factory);
}
private Connection connectToRabbitMQ(ConnectionFactory factory) throws TimeoutException, InterruptedException {
Connection conn = null;
// if the connection has not been established, retry connection
for (int retryNum = 100; retryNum >= 0; retryNum--) {
try {
conn = factory.newConnection("rabbitmq_connection");
break;
} catch (IOException e) {
System.out.println("Waiting for Rabbitmq connection...");
Thread.sleep(5000);
}
}
if (conn == null){
throw new IllegalStateException("Couldn't establish connection to rabbitMQ");
}
return conn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment