RabbitMQ - Connect to RabbitMQ in Java

Download the latest amqp-client-<version>.jar file from https://mvnrepository.com and add the JARs to your Java Build Path

Create a class that will be used to connect to RabbitMQ and add the following markup to the class. In this example, notice the setUri directive will attempt to connect to server1.example.com on port 5671 to the "foo" virtual host as john.doe.

package my.pkg;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

public class connect {

  public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException {

    ConnectionFactory cf = new ConnectionFactory();

    // use amqp if the server is not using SSL (e.g. http)
    // use amqps if the server is using SSL (e.g. https)

    Connection conn = null;
    try {
      System.out.println("trying to connect");
      conn = cf.newConnection();
    catch (Exception e) {
    finally {    
      if (conn != null) {    
        System.out.println("connection successfully created");
        try {
        catch (Exception e) {
        finally {
          System.out.println("connection successfully closed");
      else {
        System.out.println("connection failed");   		  


Or instead of using setUri, the following can be used.


# If useSslProtocol is not used, an unsecured connection will be made using AMQP
# If useSslProtocol is used, a secured SSL connection will be made using AMQPS


Run the application in Eclipse and if the connection to IBM MQ is successful, something like this should be displayed.

connection successful


Likewise, the main RabbitMQ log file should have something like this.

accepting AMQP connection <0.7993.1338> ( ->

connection <0.7993.1338> ( -> user 'john.doe' authenticated and granted access to vhost '/'

closing AMQP connection <0.21250.1339> ( ->, vhost: '/', user: 'john.doe')


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 6ac25 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |