Example usage for com.rabbitmq.client Connection close

List of usage examples for com.rabbitmq.client Connection close

Introduction

In this page you can find the example usage for com.rabbitmq.client Connection close.

Prototype

@Override
void close() throws IOException;

Source Link

Document

Close this connection and all its channels with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:Colas.Colas.java

private void sender(String string) {
    try {//from   ww w.ja va2 s.  c om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("valencia");
        factory.setPassword("admin123");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("SC", false, false, false, null);

        channel.basicPublish("", "SC", null, string.getBytes());
        System.out.println(" [x] Sent '" + string + "'");
        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error enviando ");
        e.printStackTrace();
    }
}

From source file:com.anteam.demo.rabbitmq.RabbitMQProducer.java

License:Apache License

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

    // //  w ww .  j a  va  2  s.com
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    // 
    Connection connection = factory.newConnection();

    // ??
    Channel channel = connection.createChannel();

    // ?
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    String message = "Hello World!";

    // ???Exchange??""?
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

    System.out.println(" [x] Sent '" + message + "'");

    // ??
    channel.close();
    connection.close();

}

From source file:com.anton.dev.tqrb.MessageProducer.java

public static void main(String[] args) throws IOException, TimeoutException {

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

    channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    String message = "Hola!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Enviar '" + message + "'");
    channel.close();//from w  w  w  . j av a 2s  .  co m
    connection.close();
}

From source file:com.arakelian.docker.junit.RabbitIntegrationTest.java

License:Apache License

@Test
public void testConnectsToDocker() throws ExecutionException, RetryException {
    final Retryer<Void> retryer = RetryerBuilder.<Void>newBuilder() //
            .retryIfException() //
            .withStopStrategy(StopStrategies.stopAfterDelay(1, TimeUnit.MINUTES)) //
            .withWaitStrategy(WaitStrategies.fixedWait(5, TimeUnit.SECONDS)) //
            .build();//  ww w.j a  v  a2s . c o  m

    // wait for RabbitMQ
    retryer.call(() -> {
        final ConnectionFactory factory = new ConnectionFactory();
        final Container container = rabbitmq.getContainer();
        final Binding binding = container.getPortBinding("5672/tcp");
        factory.setHost(binding.getHost());
        factory.setPort(binding.getPort());
        final Connection connection = factory.newConnection();
        connection.close();
        return null;
    });
}

From source file:com.audaexplore.b2b.GenAddFnol.java

private void publishFnol(List<Fnol> fnolList) {
    String amqpURI = null;//w  w  w  .  j  a v  a  2 s.c o m
    ConnectionFactory factory = null;
    Channel channel = null;
    Connection connection = null;
    String message;
    String BOUND_SERVICES_ENV_VARIABLE_NAME = "VCAP_SERVICES";
    Map<String, String> env = System.getenv();
    String boundServicesJson = env.get(BOUND_SERVICES_ENV_VARIABLE_NAME);
    //String boundServicesJson="{\"staging_env_json\":{},\"running_env_json\":{},\"system_env_json\":{\"VCAP_SERVICES\":{\"cloudamqp\":[{\"name\":\"MQRabbit\",\"label\":\"cloudamqp\",\"tags\":[\"Web-based\",\"UserProvisioning\",\"MessagingandQueuing\",\"amqp\",\"Backup\",\"SingleSign-On\",\"NewProduct\",\"rabbitmq\",\"CertifiedApplications\",\"Android\",\"DeveloperTools\",\"DevelopmentandTestTools\",\"Buyable\",\"Messaging\",\"Importable\",\"ITManagement\"],\"plan\":\"lemur\",\"credentials\":{\"uri\":\"amqp://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/kujcbqju\",\"http_api_uri\":\"https://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/api/\"}}],\"newrelic\":[{\"name\":\"NewRelic\",\"label\":\"newrelic\",\"tags\":[\"Monitoring\"],\"plan\":\"standard\",\"credentials\":{\"licenseKey\":\"a8a96a124d1b58d708a2c4c07c6cff8938e2e2f4\"}}],\"mongolab\":[{\"name\":\"MongoDB\",\"label\":\"mongolab\",\"tags\":[\"DataStore\",\"document\",\"mongodb\"],\"plan\":\"sandbox\",\"credentials\":{\"uri\":\"mongodb://CloudFoundry_31lvrquo_j44bi0vu_3gjp7i4s:6RAtFVBfQUCe_DV7LAq5uCffOXaEXdly@ds047315.mongolab.com:47315/CloudFoundry_31lvrquo_j44bi0vu\"}}]}},\"application_env_json\":{\"VCAP_APPLICATION\":{\"limits\":{\"mem\":512,\"disk\":1024,\"fds\":16384},\"application_id\":\"87bdc475-83c4-4df9-92d1-40ff9bf82249\",\"application_version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"application_name\":\"vinservice\",\"application_uris\":[\"vinservice.cfapps.io\"],\"version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"name\":\"vinservice\",\"space_name\":\"development\",\"space_id\":\"d33d438c-860a-46d3-ab33-4c2efac841be\",\"uris\":[\"vinservice.cfapps.io\"],\"users\":null}}}";

    if (StringUtils.isNotBlank(boundServicesJson)) {
        //amqpURI =  JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri",String.class);
        JSONArray jsonArray = JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri");
        amqpURI = jsonArray.get(0).toString();
    } else {
        amqpURI = "amqp://localhost";
    }

    System.out.println("Sending messages to " + amqpURI);
    //System.exit(0);

    try {
        factory = new ConnectionFactory();
        factory.setUri(amqpURI);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("fnol", true, false, false, null);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (TimeoutException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (KeyManagementException e1) {
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }

    for (Fnol fnol : fnolList) {
        message = new Gson().toJson(fnol);

        try {
            channel.basicPublish("amq.direct", "fnolKey",
                    new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(2).build(),
                    //MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());
            System.out.println("message " + message + " was published");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        channel.close();
        connection.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.audaexplore.b2b.GenAddFnol.java

private void publishCars(List<Car> carList) {
    String amqpURI = null;/*  w ww . java2  s  .c  o m*/
    ConnectionFactory factory = null;
    Channel channel = null;
    Connection connection = null;
    String message;
    String BOUND_SERVICES_ENV_VARIABLE_NAME = "VCAP_SERVICES";
    Map<String, String> env = System.getenv();
    String boundServicesJson = env.get(BOUND_SERVICES_ENV_VARIABLE_NAME);
    //String boundServicesJson="{\"staging_env_json\":{},\"running_env_json\":{},\"system_env_json\":{\"VCAP_SERVICES\":{\"cloudamqp\":[{\"name\":\"MQRabbit\",\"label\":\"cloudamqp\",\"tags\":[\"Web-based\",\"UserProvisioning\",\"MessagingandQueuing\",\"amqp\",\"Backup\",\"SingleSign-On\",\"NewProduct\",\"rabbitmq\",\"CertifiedApplications\",\"Android\",\"DeveloperTools\",\"DevelopmentandTestTools\",\"Buyable\",\"Messaging\",\"Importable\",\"ITManagement\"],\"plan\":\"lemur\",\"credentials\":{\"uri\":\"amqp://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/kujcbqju\",\"http_api_uri\":\"https://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/api/\"}}],\"newrelic\":[{\"name\":\"NewRelic\",\"label\":\"newrelic\",\"tags\":[\"Monitoring\"],\"plan\":\"standard\",\"credentials\":{\"licenseKey\":\"a8a96a124d1b58d708a2c4c07c6cff8938e2e2f4\"}}],\"mongolab\":[{\"name\":\"MongoDB\",\"label\":\"mongolab\",\"tags\":[\"DataStore\",\"document\",\"mongodb\"],\"plan\":\"sandbox\",\"credentials\":{\"uri\":\"mongodb://CloudFoundry_31lvrquo_j44bi0vu_3gjp7i4s:6RAtFVBfQUCe_DV7LAq5uCffOXaEXdly@ds047315.mongolab.com:47315/CloudFoundry_31lvrquo_j44bi0vu\"}}]}},\"application_env_json\":{\"VCAP_APPLICATION\":{\"limits\":{\"mem\":512,\"disk\":1024,\"fds\":16384},\"application_id\":\"87bdc475-83c4-4df9-92d1-40ff9bf82249\",\"application_version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"application_name\":\"vinservice\",\"application_uris\":[\"vinservice.cfapps.io\"],\"version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"name\":\"vinservice\",\"space_name\":\"development\",\"space_id\":\"d33d438c-860a-46d3-ab33-4c2efac841be\",\"uris\":[\"vinservice.cfapps.io\"],\"users\":null}}}";

    if (StringUtils.isNotBlank(boundServicesJson)) {
        //amqpURI =  JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri",String.class);
        JSONArray jsonArray = JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri");
        amqpURI = jsonArray.get(0).toString();
    } else {
        amqpURI = "amqp://localhost";
    }

    System.out.println("Sending messages to " + amqpURI);
    //System.exit(0);

    try {
        factory = new ConnectionFactory();
        factory.setUri(amqpURI);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("fnol", true, false, false, null);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (TimeoutException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (KeyManagementException e1) {
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }

    for (Car car : carList) {
        message = new Gson().toJson(car);

        try {
            channel.basicPublish("amq.direct", "fnolKey",
                    new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(2).build(),
                    //MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());
            System.out.println("message " + message + " was published");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        channel.close();
        connection.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.caucho.v5.pipe.rabbit.RabbitPipeImpl.java

License:Open Source License

private void closeConnection() {
    if (_conn != null) {
        try {//from ww w . j  av a  2 s.  c om
            Connection conn = _conn;
            _conn = null;

            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.colm.app.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Connection connection;
    Channel channel;/*from w w  w  .  java 2  s.  co  m*/
    String replyQueueName;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.0.13");
    factory.setPassword("admin");
    factory.setUsername("admin");
    factory.setVirtualHost("admin");
    connection = factory.newConnection();
    channel = connection.createChannel();
    String queneNAme = "rabbitmq_test";
    channel.queueDeclare(queneNAme, false, false, false, null);
    String message = "Something Else";
    for (int i = 0; i < 1000; i++) {
        channel.basicPublish("", queneNAme, null, message.getBytes());
    }
    System.out.println("Sent '" + message + "'");
    channel.close();
    connection.close();

}

From source file:com.DeadLetterSender.java

License:Open Source License

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);/*from  w w  w .j  a va 2 s  . c o  m*/
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    // Request Message
    String message = "<soapenv:Envelope" + " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "<soapenv:Body>\n" + "  <p:greet xmlns:p=\"http://service.wso2.org\">\n" + "     <in>" + "IBM"
            + "</in>\n" + "  </p:greet>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>";

    // Adding Message Properties
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.messageId("007");
    builder.contentType("text/xml");
    builder.correlationId("1111");
    builder.replyTo(REPLY_QUEUE_NAME);
    builder.contentEncoding("UTF-8");

    // Custom user properties
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("SOAP_ACTION", "getQuote");
    builder.headers(headers);

    // Publish the message to exchange
    channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, builder.build(), message.getBytes());
    channel.close();
    connection.close();
}

From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java

License:Apache License

/**
 * This method is used to check for checking exchange availability, if
 * exchange is not available creates a new exchange based on isCreateExchangeIfNotExisting true boolean property  .
 * @throws RemRemPublishException//from   w  w w.  ja v a 2 s .c om
 * @throws TimeoutException
 * @throws IOException
 */
public void checkAndCreateExchangeIfNeeded() throws RemRemPublishException {
    final boolean exchangeAlreadyExist = hasExchange();
    if (!exchangeAlreadyExist) {
        if (isCreateExchangeIfNotExisting()) {
            Connection connection = null;
            try {
                connection = factory.newConnection();
            } catch (final IOException | TimeoutException e) {
                throw new RemRemPublishException("Exception occurred while creating Rabbitmq connection ::"
                        + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            }
            Channel channel = null;
            try {
                channel = connection.createChannel();
            } catch (final IOException e) {
                throw new RemRemPublishException(
                        "Exception occurred while creating Channel with Rabbitmq connection ::"
                                + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            }
            try {
                channel.exchangeDeclare(exchangeName, "topic", true);
            } catch (final IOException e) {
                log.info(exchangeName + "failed to create an exchange");
                throw new RemRemPublishException("Unable to create Exchange with Rabbitmq connection "
                        + exchangeName + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            } finally {
                if (channel == null || channel.isOpen()) {
                    try {
                        channel.close();
                        connection.close();
                    } catch (IOException | TimeoutException e) {
                        log.warn("Exception occurred while closing the channel" + e.getMessage());
                    }
                }
            }
        } else {
            if (!Boolean.getBoolean(PropertiesConfig.CLI_MODE)) {
                throw new RemRemPublishException(
                        exchangeName + PropertiesConfig.INVALID_EXCHANGE_MESSAGE_SERVICE);
            } else {
                throw new RemRemPublishException(
                        "Exchange " + exchangeName + PropertiesConfig.INVALID_EXCHANGE_MESSAGE_CLI);
            }
        }
    }
}