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:org.hobbit.core.rabbit.EchoServer.java

License:Open Source License

@Override
public void run() {
    running = true;/*  ww w  .ja v  a2s. co  m*/
    Connection connection = null;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(rabbitHost);
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.basicQos(1);
        channel.queueDeclare(queueName, false, false, true, null);

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(properties.getCorrelationId()).deliveryMode(2).build();
                channel.basicPublish("", properties.getReplyTo(), replyProps, body);
            }
        };
        channel.basicConsume(queueName, true, consumer);

        while (running) {
            Thread.sleep(3000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.hobbit.core.rabbit.ParallelizationTest.java

License:Open Source License

@Test
public void test() throws InterruptedException, IOException, TimeoutException {

    EchoServer server = new EchoServer(TestConstants.RABBIT_HOST, REQUEST_QUEUE_NAME);

    Thread serverThread = new Thread(server);
    serverThread.start();//  w w w . ja  v  a  2  s.c om
    System.out.println("Server started.");

    Random rand = new Random();
    Thread clientThreads[] = new Thread[NUMBER_OF_CLIENTS];
    RabbitRpcClient client = null;
    Connection connection = null;
    long time;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(TestConstants.RABBIT_HOST);
        connection = factory.newConnection();
        client = RabbitRpcClient.create(connection, REQUEST_QUEUE_NAME);
        for (int i = 0; i < clientThreads.length; ++i) {
            clientThreads[i] = new Thread(
                    new RpcClientBasedEchoClient(client, NUMBER_OF_MSGS, rand.nextLong()));
        }

        Timer timer = new Timer();
        final Thread testThread = Thread.currentThread();
        timer.schedule(new TimerTask() {
            @SuppressWarnings("deprecation")
            @Override
            public void run() {
                testThread.stop();
            }
        }, MAX_RUNTIME);

        time = System.currentTimeMillis();
        for (int i = 0; i < clientThreads.length; ++i) {
            clientThreads[i].start();
            System.out.print("Client #");
            System.out.print(i);
            System.out.println(" started.");
        }
        for (int i = 0; i < clientThreads.length; ++i) {
            clientThreads[i].join();
            System.out.print("Client #");
            System.out.print(i);
            System.out.println(" terminated.");
        }
        server.setRunning(false);
        serverThread.join();
        timer.cancel();

        time = System.currentTimeMillis() - time;
        System.out.println("Server terminated.");
        System.out.println("runtime : " + time + "ms");
    } finally {
        if (client != null) {
            client.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.ninjav.rabbitmq.SendTest.java

@Test
public void canSendMessageToQueue() throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    for (int i = 0; i < 1000000; i++) {
        String message = "Hello world " + i;
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    }// www .j  a va  2 s . com

    channel.close();
    connection.close();
}

From source file:org.openbaton.common.vnfm_sdk.amqp.AbstractVnfmSpringAmqp.java

License:Apache License

@Override
protected void unregister() {
    try {//from ww w  .  j a v a2 s . c  o m
        ((VnfmSpringHelperRabbit) vnfmHelper).sendMessageToQueue(RabbitConfiguration.queueName_vnfmUnregister,
                vnfmManagerEndpoint);
    } catch (IllegalStateException e) {
        log.warn("Got exception while unregistering trying to do it manually");
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost(rabbitHost);
        Connection connection = null;
        try {
            connection = factory.newConnection();

            Channel channel = connection.createChannel();

            String message = gson.toJson(vnfmManagerEndpoint);
            channel.basicPublish("openbaton-exchange", RabbitConfiguration.queueName_vnfmUnregister,
                    MessageProperties.TEXT_PLAIN, message.getBytes("UTF-8"));
            log.debug("Sent '" + message + "'");

            channel.close();
            connection.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:org.opendaylight.federationmessagequeue.impl.RabbitMessageBus.java

License:Open Source License

@Override
public void destroyQueue(String queueName) {
    LOG.info("Started delete of queue {}", queueName);

    // lookup connection by queueName
    MessageBusConnectionData messageBusConnectionData = queueNameToConnectionData.get(queueName);
    if (messageBusConnectionData != null) {
        // get channel from active connections map
        Channel channel = messageBusConnectionData.channel;
        String brokerIp = messageBusConnectionData.brokerIp;
        Connection conn = messageBusConnectionData.conn;
        try {/* www  .jav a2 s  .  c om*/
            // kill the queue dont wait for confirmation
            if (channel != null) {
                try {
                    channel.queueDelete(queueName);
                    LOG.info("Deleted queue {} successfully", queueName);
                } catch (IOException e) {
                    LOG.warn("Failed to delete queue {} msg: {}", queueName, e.getMessage());
                }
                channel.close();
            } else {
                LOG.warn("Null channel while deleting queue {} on broker {}", queueName, brokerIp);
            }
            if (conn != null) {
                conn.close();
            } else {
                LOG.warn("Null connection while deleting queue {} on broker {}", queueName, brokerIp);
            }
        } catch (IOException | TimeoutException e) {
            LOG.warn("Failed to close channel while deleting queue {} on broker {}", queueName, brokerIp, e);
        }
        // remove the queue from the internal queue list
        queueNameToConnectionData.remove(queueName);
    } else {
        LOG.warn("Cancelled deletion of queue {} because queueName not found in queueNameToConnectionData",
                queueName);
    }

}

From source file:org.openmrs.module.amqpmodule.utils.impl.PublisherServiceImpl.java

License:Open Source License

@Override
public boolean PublisherCreateConnection() throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.43.123");
    factory.setPort(5672);/*from  w  w  w  .  j  a  v  a  2s .c  om*/
    factory.setUsername("chs");
    factory.setPassword("chs123");
    Connection connection = null;
    try {
        connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);

        channel.basicPublish(EXCHANGE_NAME, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
        System.out.println(" [x] Sent '" + msg + "'");

        channel.close();

    } catch (TimeoutException e) {
        System.out.println("Connection Timed out");
        e.printStackTrace();
    }

    connection.close();

    return true;
}

From source file:org.opennaas.extensions.genericnetwork.capability.nclprovisioner.components.NetworkObservationsPusher.java

License:Apache License

private void sendStatistics(String topicName, String csvMessage)
        throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, IOException {

    Connection conn = null;
    Channel channel = null;//  w w w. j a va  2 s. co m

    try {

        log.debug("Establishing RabbitMQ connection with sla manager with URI: " + slaManagerUri);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(slaManagerUri.getHost());

        conn = factory.newConnection();
        channel = conn.createChannel();

        channel.exchangeDeclare(topicName, "direct");

        log.debug("Publishing message in RabbitMQ channel.");

        channel.basicPublish(topicName, RABBIT_MQ_ROUTING_KEY,
                new AMQP.BasicProperties.Builder().contentType(OBSERVATIONS_CONTENT_TYPE).build(),
                csvMessage.getBytes());

        log.debug("Message successfully sent to SLA manager.");

    } finally {
        if (channel != null && channel.isOpen())
            channel.close();
        if (conn != null && conn.isOpen())
            conn.close();

        log.debug("Connection to RabbitMQ server closed.");

    }

}

From source file:org.pushtrigger.mule.agent.CreateQueueAgent.java

License:Apache License

@Override
public void start() throws MuleException {
    System.out.println("Create Queue Agent is running...");

    Connection connection = null;
    Channel channel = null;//w w w . ja v  a 2s  . c  o  m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World! I am creating a queue...";

        Map<String, Object> props = new HashMap<String, Object>();
        props.put("path", "queue");
        props.put("branch", "create");

        AMQP.BasicProperties.Builder bob = new AMQP.BasicProperties.Builder();
        AMQP.BasicProperties basicProps = bob.headers(props).build();

        channel.basicPublish("", QUEUE_NAME, basicProps, message.getBytes());
        System.out.println("Agent has created the queue...");
    } catch (IOException e) {
        System.out.println("Something wrong " + e);
    } finally {
        try {
            if (channel != null)
                channel.close();
        } catch (IOException e) {
        }
        try {
            if (connection != null)
                connection.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.sdw.scheduler.PeriodicUpdater.java

License:Apache License

/**
 * Pushes messages to the shared queue on execution of triggers
 * @param JobExecutionContext Job execution context
 * @throws JobExecutionException //from   ww w  .jav  a 2 s.  c  om
 */
@Override
public void execute(JobExecutionContext jobExecutionContext) {
    try {
        Connection connection = PeriodicScheduler.factory.newConnection();
        Channel channel = connection.createChannel();
        String queueName = "work-queue-1";
        Map<String, Object> params = new HashMap<>();
        params.put("x-ha-policy", "all");
        channel.queueDeclare(queueName, true, false, false, params);
        String mesg = "Sent at: " + System.currentTimeMillis();
        byte[] body = mesg.getBytes("UTF-8");
        channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, body);
        LOG.info("Message sent: " + mesg);
        connection.close();
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:org.springframework.amqp.rabbit.connection.CachePropertiesTests.java

License:Apache License

@Test
public void testConnectionCache() throws Exception {
    Connection c1 = this.connectionCf.createConnection();
    Connection c2 = this.connectionCf.createConnection();
    Channel ch1 = c1.createChannel(false);
    Channel ch2 = c1.createChannel(false);
    Channel ch3 = c2.createChannel(true);
    Channel ch4 = c2.createChannel(true);
    Channel ch5 = c2.createChannel(false);
    ch1.close();/*from  www  .  j  a  v  a  2  s.c  om*/
    ch2.close();
    ch3.close();
    ch4.close();
    ch5.close();
    c1.close();
    Properties props = this.connectionCf.getCacheProperties();
    assertEquals("10", props.getProperty("channelCacheSize"));
    assertEquals("5", props.getProperty("connectionCacheSize"));
    assertEquals("2", props.getProperty("openConnections"));
    assertEquals("1", props.getProperty("idleConnections"));
    c2.close();
    props = this.connectionCf.getCacheProperties();
    assertEquals("2", props.getProperty("idleConnections"));
    assertEquals("2", props.getProperty("idleConnectionsHighWater"));
    int c1Port = c1.getLocalPort();
    int c2Port = c2.getLocalPort();
    assertEquals("2", props.getProperty("idleChannelsNotTx:" + c1Port));
    assertEquals("0", props.getProperty("idleChannelsTx:" + c1Port));
    assertEquals("2", props.getProperty("idleChannelsNotTxHighWater:" + c1Port));
    assertEquals("0", props.getProperty("idleChannelsTxHighWater:" + c1Port));
    assertEquals("1", props.getProperty("idleChannelsNotTx:" + c2Port));
    assertEquals("2", props.getProperty("idleChannelsTx:" + c2Port));
    assertEquals("1", props.getProperty("idleChannelsNotTxHighWater:" + c2Port));
    assertEquals("2", props.getProperty("idleChannelsTxHighWater:" + c2Port));
}