Example usage for com.rabbitmq.client Channel close

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

Introduction

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

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

Close this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:joram.amqp.PersistenceKillTest.java

License:Open Source License

public void killingTest() throws Exception {
    senderConnection = new LiveServerConnection("sender", "localhost", 5672, null, null);
    receiverConnection = new LiveServerConnection("receiver", "localhost", 5672, null, null);

    senderConnection.startLiveConnection();
    receiverConnection.startLiveConnection();

    Channel senderChannel = senderConnection.getConnection().createChannel();
    senderChannel.txSelect();//w w  w . j  av  a2 s.co m

    DeclareOk declareOk = senderChannel.queueDeclare("testQueue", true, false, false, null);

    new Thread(new Runnable() {

        int received;
        long totalReceived;

        Channel consumerChannel;
        QueueingConsumer consumer;

        // Consumer thread
        public void run() {

            try {
                consumerChannel = receiverConnection.getConnection().createChannel();
                consumerChannel.txSelect();
                consumer = new QueueingConsumer(consumerChannel);
                consumerChannel.basicConsume("testQueue", false, consumer);
            } catch (Exception exc) {
                exc.printStackTrace();
            }

            while (true) {
                QueueingConsumer.Delivery delivery;
                try {
                    delivery = consumer.nextDelivery();
                    long receivedNb = Long.parseLong(new String(delivery.getBody()));
                    consumer.getChannel().basicAck(delivery.getEnvelope().getDeliveryTag(), false);

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException exc1) {
                    }

                    if (receivedNb < totalReceived) {
                        System.out.println("Duplicate received: " + receivedNb);
                        continue;
                    }

                    // We can receive duplicates but can't miss one message
                    // One duplicate if the channel is transacted, multiple if it is not
                    assertEquals(totalReceived, receivedNb);

                    totalReceived++;
                    received++;

                    consumerChannel.txCommit();

                    if (received == nbMsgRound) {
                        received = 0;
                        synchronized (lock) {
                            lock.notify();
                        }
                    }

                    if (totalReceived == nbMsgRound * nbRounds) {
                        consumer.getChannel().close();
                        return;
                    }

                } catch (Exception ie) {
                    if (totalReceived == nbRounds * nbMsgRound) {
                        return;
                    }
                    System.out.println("Consumer connection broken. Reconnect.");
                    while (!receiverConnection.isConnectionOpen()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException exc) {
                            exc.printStackTrace();
                        }
                    }
                    try {
                        consumerChannel = receiverConnection.getConnection().createChannel();
                        consumerChannel.txSelect();
                        consumer = new QueueingConsumer(consumerChannel);
                        consumerChannel.basicConsume("testQueue", false, consumer);
                    } catch (IOException exc) {
                        exc.printStackTrace();
                    }
                    System.out.println("Consumer Reconnected --- totalReceived = " + totalReceived);
                    continue;
                }
            }
        }
    }).start();

    long start = System.nanoTime();

    // Killer thread
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(5000);
                System.out.println("Kill server");
                killAgentServer((short) 0);

                Thread.sleep(5000);
                startAgentServer((short) 0);
                System.out.println("server restarted.");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }).start();

    // Sender
    for (int i = 0; i < nbRounds; i++) {
        if (i % 20 == 0) {
            long delta = System.nanoTime() - start;
            System.out.println("Round " + i + " " + ((i * nbMsgRound * 1000000000L) / delta) + " msg/s");
        }
        try {
            for (int j = 0; j < nbMsgRound; j++) {
                senderChannel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                        new Long(i * nbMsgRound + j).toString().getBytes());
            }

            synchronized (lock) {
                senderChannel.txCommit();
                lock.wait();
            }
        } catch (Exception exc) {
            i--;
            System.out.println("Sender connection broken. Reconnect.");
            while (!senderConnection.isConnectionOpen()) {
                Thread.sleep(100);
            }
            senderChannel = senderConnection.getConnection().createChannel();
            senderChannel.txSelect();
            System.out.println("Sender Reconnected");
            Thread.sleep(1000);
            System.out.println("Restart Sender");
        }
    }

    long delta = System.nanoTime() - start;
    System.out.println(delta / 1000000L + " ms");
    System.out.println(((nbRounds * nbMsgRound * 1000000000L) / delta) + " msg/s");

    senderChannel.queueDelete(declareOk.getQueue());

    senderChannel.close();

    senderConnection.stopLiveConnection();
    receiverConnection.stopLiveConnection();

}

From source file:loanbroker.Aggregator.java

private void send(entity.Message m, String routingKey)
        throws IOException, TimeoutException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);//from   w  w  w .jav  a  2 s.c o  m
    factory.setPort(5672);
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(ExchangeName.GLOBAL, "direct");

    //creating LoanResponse object
    LoanResponse lp = new LoanResponse(parseInt(m.getSsn()), m.getCreditScore(), m.getLoanDuration(), "");

    Gson gson = new GsonBuilder().create();
    String fm = gson.toJson(lp);
    BasicProperties props = new BasicProperties.Builder().build();

    channel.basicPublish(ExchangeName.GLOBAL, routingKey, props, fm.getBytes());

    System.out.println(" [x] Sent '" + ExchangeName.GLOBAL + routingKey + "':'" + fm + "'");

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

}

From source file:loanbroker.GetCreditScore.java

public void send(entity.Message creditScoreMessage) throws IOException, TimeoutException, Exception {
    ConnectionFactory connfac = new ConnectionFactory();
    connfac.setHost(hostName);/*from   w  ww.  j a va  2  s.  co m*/
    connfac.setPort(5672);
    connfac.setUsername("student");
    connfac.setPassword("cph");
    Gson gson = new GsonBuilder().create();

    String fm = gson.toJson(creditScoreMessage);

    Connection connection = connfac.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(ExchangeName.OUTPUT_GET_CREDITSCORE, "fanout");
    channel.basicPublish(ExchangeName.OUTPUT_GET_CREDITSCORE, "", null, fm.getBytes());

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

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

}

From source file:loanbroker.normalizer.CallTeachersJsonBank.java

public static void main(String[] args) {
    Gson gson = new Gson();
    DtoJsonBank jsonBank = null;//from   w  w  w.j  a v a2 s .com
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        factory.setPort(5672);
        factory.setUsername("student");
        factory.setPassword("cph");

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

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        //reply
        String corrId = java.util.UUID.randomUUID().toString();
        BasicProperties props = new BasicProperties.Builder().correlationId("test1122").replyTo(replyQueueName)
                .build();

        String message = gson.toJson(new DtoJsonBank("1605789787", 598, 10.0, ""));
        channel.basicPublish(EXCHANGE_NAME, "", props, message.getBytes());

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

    } catch (IOException | TimeoutException e) {
        e.printStackTrace();
    }

}

From source file:localdomain.localhost.RabbitMQClient.java

License:Apache License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*w w w  .j  a  va 2  s  .  c  o m*/
        ConnectionFactory factory = new ConnectionFactory();
        String messages = new String();

        String uri = System.getProperty("CLOUDAMQP_URL");
        factory.setUri(uri);

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

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        QueueingConsumer consumer = new QueueingConsumer(channel);

        boolean autoACK = false;
        channel.basicConsume(QUEUE_NAME, autoACK, consumer);

        System.out.println(" [*] Waiting 100ms for a message");
        QueueingConsumer.Delivery delivery = consumer.nextDelivery(100);

        while (delivery != null) {
            String message = new String(delivery.getBody());

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

            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

            messages = message + " <br/> " + messages;
            delivery = consumer.nextDelivery(100);
        }
        request.setAttribute("messages", messages);
        request.getRequestDispatcher("/index.jsp").forward(request, response);

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

    } catch (Exception e) {
        request.setAttribute("throwable", e);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

}

From source file:localdomain.localhost.RabbitMQServer.java

License:Apache License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from   w ww  .  j ava 2s .  c  o  m*/
        String message = request.getParameter("message");

        ConnectionFactory factory = new ConnectionFactory();
        String uri = System.getProperty("CLOUDAMQP_URL");
        factory.setUri(uri);

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

        boolean durable = true;
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);

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

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

        response.sendRedirect(request.getContextPath() + "/index.jsp");
    } catch (Exception e) {
        request.setAttribute("throwable", e);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:main.TestMain.java

public static void sendMessage(String message) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();/*www . j  a  va 2  s. c  o  m*/
}

From source file:messaging.Worker.java

License:Apache License

public static void sendMessage(String message) throws java.io.IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename());
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

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

    channel.close();
    connection.close();//from   ww w. ja  va2 s .  co  m
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  ?./* w ww. j a v  a  2s.co m*/
 * <p>
 * exchange = fanout
 * ??? topic ?
 *
 * @param topic   
 * @param message ?
 * @param confirm ??
 * @return ???rabbit confirm ?????
 */
public boolean doPublish(String topic, String message, boolean confirm) {
    Connection connection = rabbitAdapter.getConnection();
    Channel channel = connection.createChannel(false);
    Object funResult = null;
    try {
        if (confirm) {
            channel.confirmSelect();
        }
        channel.exchangeDeclare(topic, BuiltinExchangeType.FANOUT, true);
        AMQP.BasicProperties properties = new AMQP.BasicProperties("text/plain", null, getMQHeader(topic), 2, 0,
                null, null, null, null, null, null, null, null, null);
        funResult = sendBeforeFun.invoke(topic, "", properties);
        channel.basicPublish(topic, "", properties, message.getBytes());
        if (confirm) {
            try {
                return channel.waitForConfirms();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("[MQ] Rabbit publish error.", e);
                sendErrorFun.invoke(e, funResult);
                return false;
            }
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error("[MQ] Rabbit publish error.", e);
        sendErrorFun.invoke(e, funResult);
        return false;
    } finally {
        try {
            channel.close();
            sendFinishFun.invoke(funResult);
        } catch (IOException | TimeoutException e) {
            logger.error("[MQ] Rabbit publish error.", e);
        }
        connection.close();
    }
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  .//from  w  w w  . j a va  2s.co  m
 * <p>
 * exchange = fanout
 *
 * @param address ?
 * @param message ?
 * @param confirm ??
 * @return ??rabbit confirm ?????
 */
public boolean doRequest(String address, String message, boolean confirm) {
    Connection connection = rabbitAdapter.getConnection();
    Channel channel = connection.createChannel(false);
    Object funResult = null;
    try {
        if (confirm) {
            channel.confirmSelect();
        }
        channel.queueDeclare(address, true, false, false, null);
        AMQP.BasicProperties properties = new AMQP.BasicProperties("text/plain", null, getMQHeader(address), 2,
                0, null, null, null, null, null, null, null, null, null);
        funResult = sendBeforeFun.invoke("", address, properties);
        channel.basicPublish("", address, properties, message.getBytes());
        if (confirm) {
            try {
                return channel.waitForConfirms();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("[MQ] Rabbit request error.", e);
                sendErrorFun.invoke(e, funResult);
                return false;
            }
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error("[MQ] Rabbit request error.", e);
        sendErrorFun.invoke(e, funResult);
        return false;
    } finally {
        try {
            channel.close();
            sendFinishFun.invoke(funResult);
        } catch (IOException | TimeoutException e) {
            logger.error("[MQ] Rabbit request error.", e);
        }
        connection.close();
    }
}