Bootstrap FreeKB - RabbitMQ - Connect to RabbitMQ in Java
RabbitMQ - Connect to RabbitMQ in Java

Updated:   |  RabbitMQ articles

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)
    cf.setUri("amqps://john.doe:itsasecret@server1.example.com:5671/foo");

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

 

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

cf.setUsername("john.doe");
cf.setPassword("itsasecret");
cf.setVirtualHost("foo");
cf.setHost("rabbit1.example.com");
cf.setPort(5671);

# 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
cf.useSslProtocol();

 

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> (10.17.115.16:54343 -> 10.122.15.2:5672)

connection <0.7993.1338> (10.17.115.16:54343 -> 10.122.15.2:5672): user 'john.doe' authenticated and granted access to vhost '/'

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

 




Did you find this article helpful?

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



Comments


Add a Comment


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