Example usage for com.rabbitmq.client Connection createChannel

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

Introduction

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

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:RabbitMQsender.java

public void send(String[] args) {

    if (args.length != 4) {
        logger.warn(/*from ww w.j a va2  s .  co  m*/
                "Bad number of arguments, Sender needs String hostURL, String queueName, String fileName, int sleepTime");
        return;
    }

    String hostURL = args[0];
    String queueName = args[1];
    String fileName = args[2];
    int sleepTime = Integer.parseInt(args[3]);
    File myFile = new File(fileName);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostURL);

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

        //send contents of file
        FileReader inputFile = new FileReader(myFile);
        BufferedReader bufferReader = new BufferedReader(inputFile);
        String line = bufferReader.readLine();

        logger.info("Sending file contents");

        do {
            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
            if (line != null) {
                String toSend = addTimestamp(line);
                this.publish(channel, queueName, toSend); //will be dropped till queue is declared (so, declare)
                if (logger.isDebugEnabled()) {
                    logger.debug("Sending '" + toSend + "' from file " + myFile.getAbsolutePath());
                }
                line = bufferReader.readLine();
            }
        } while (line != null);
        bufferReader.close();
        channel.close();
        connection.close();
    } catch (Exception ex) {
        logger.error("Error while reading file line by line: " + ex.getMessage());
        return;
    }
    logger.info("Everything sent without errors\n");
}

From source file:amqp.AmqpClient.java

License:Apache License

/**
 * This method will block until a connection and channel can be established to the AMQP broker as specified
 * by the {@link #connectionFactory} or it has tried the maximum number of times.
 *
 * @param maximumRetryAttempts number of times to try a reconnect when we can't contact the broker.
 * @return Channel to the broker or null if we have tried the maximum number of times to connect
 * @throws InterruptedException if any thread has interrupted the current thread.
 *//*from  w  w w . j  a  v a2s .c o m*/
protected Channel getChannel(int maximumRetryAttempts) throws InterruptedException {
    Channel channel = null;
    Thread thread = Thread.currentThread();
    int numberTimesConnectionLost = 0;

    while (channel == null && isRunning() && !thread.isInterrupted()) {
        Connection conn = null;
        try {
            LOG.info("Connecting to broker at {}...", connectionFactory.getHost());
            conn = connectionFactory.newConnection();
            LOG.info("Connected to broker at {}", connectionFactory.getHost());

            channel = conn.createChannel();
            // reset backoff time
            numberTimesConnectionLost = 0;
        } catch (IOException e) {
            LOG.info("IOException caught. Closing connection to broker and waiting to reconnect", e);
            closeConnectionSilently(conn);

            // increment connection lost count
            numberTimesConnectionLost++;
            if (numberTimesConnectionLost > maximumRetryAttempts) {
                break;
            }
            waitToRetryConnection(numberTimesConnectionLost);
        }
    }

    if (thread.isInterrupted()) {
        throw new InterruptedException();
    }

    return channel;
}

From source file:at.ac.tuwien.dsg.cloud.utilities.messaging.lightweight.rabbitMq.channel.ReceivingChannelTest.java

@Test
public void testLazyBindType() throws Exception {
    Discovery discovery = Mockito.mock(Discovery.class);
    Serializer serializer = Mockito.mock(Serializer.class);
    RabbitMqFactory rabbitMqFactory = Mockito.mock(RabbitMqFactory.class);

    ConnectionFactory factory = Mockito.mock(ConnectionFactory.class);
    Connection connection = Mockito.mock(Connection.class);
    Channel channel = Mockito.mock(Channel.class);
    DeclareOk declareOk = Mockito.mock(DeclareOk.class);
    QueueingConsumer consumer = Mockito.mock(QueueingConsumer.class);
    Delivery delivery = Mockito.mock(Delivery.class);
    RabbitMqMessage msg = Mockito.mock(RabbitMqMessage.class);

    String expectedQueue = "testQueue";

    Mockito.when(discovery.discoverHost()).thenReturn("localhost");
    Mockito.when(rabbitMqFactory.getConnectionFactory()).thenReturn(factory);
    Mockito.when(factory.newConnection()).thenReturn(connection);
    Mockito.when(rabbitMqFactory.getQueueingConsumer(channel)).thenReturn(consumer);
    Mockito.when(connection.createChannel()).thenReturn(channel);
    Mockito.when(channel.queueDeclare()).thenReturn(declareOk);
    Mockito.when(declareOk.getQueue()).thenReturn(expectedQueue);
    Mockito.when(consumer.getChannel()).thenReturn(channel);
    Mockito.when(consumer.nextDelivery()).thenReturn(delivery);
    Mockito.when(delivery.getBody()).thenReturn("test".getBytes());
    Mockito.when(serializer.deserilize("test".getBytes(), RabbitMqMessage.class)).thenReturn(msg);

    ReceivingChannel subject = new ReceivingChannel(discovery, serializer, rabbitMqFactory);

    String expectedRoutingKey1 = "testType1";
    String expectedRoutingKey2 = "testType2";

    subject.bindType(expectedRoutingKey1);
    subject.bindType(expectedRoutingKey2);

    //due to lazy startup binding should not yet have been triggered
    Mockito.verify(channel, Mockito.never()).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey1);/*from   w w  w  .j a v  a 2  s. c o  m*/

    Mockito.verify(channel, Mockito.never()).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey2);

    //this call should trigger the binding to the queues
    RabbitMqMessage msgActual = subject.getDelivery();

    Mockito.verify(channel, Mockito.times(1)).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey1);

    Mockito.verify(channel, Mockito.times(1)).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey2);

    Assert.assertEquals(msg, msgActual);
}

From source file:bank.OurRabbitBank.java

public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.OUR_JSON_BANK);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        AMQP.BasicProperties properties = delivery.getProperties();
        String message = new String(delivery.getBody());

        Gson g = new Gson();

        Message msg = g.fromJson(message, Message.class);

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

        sendToNormalizer(msg, properties);
    }//from  w  w w.  j a  va2 s. co m
}

From source file:bank.OurRabbitBank.java

private static void sendToNormalizer(Message msg, AMQP.BasicProperties props) {
    try {//www . j av a  2 s .  c o  m
        Gson g = new Gson();
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //channel.exchangeDeclare(ExchangeName.OUR_JSON_BANK_RESPONSE, "direct");

        int ssn = Integer.valueOf(msg.getSsn());
        double interestRate = calcRate();
        String bank = "OurRabbitBank";
        String correlationId = props.getCorrelationId();

        LoanResponse response = new LoanResponse(ssn, interestRate, bank, correlationId);

        String res = g.toJson(response);

        channel.basicPublish(ExchangeName.OUR_JSON_BANK_RESPONSE, "", props, res.getBytes());

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

        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error in OutRabbitBank: " + e.getMessage());
    }
}

From source file:benchmarkio.consumer.rabbitmq.RabbitMQMessageConsumer.java

License:Apache License

public RabbitMQMessageConsumer(final String host, final int port, final String topic, final boolean durable) {
    Preconditions.checkNotNull(host);//from  w  w w. java 2s . c  o m
    Preconditions.checkNotNull(topic, "topic cannot be null");

    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);

    try {
        final Connection connection = factory.newConnection();

        this.channel = connection.createChannel();
        this.channel.exchangeDeclare(topic, "topic", durable);
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }

    this.topic = topic;
    this.histogram = Histograms.create();
}

From source file:benchmarkio.producer.rabbitmq.RabbitMQMessageProducer.java

License:Apache License

public RabbitMQMessageProducer(final String host, final int port, final String topic, final String message,
        final long numberOfMessagesToProduce, final boolean durable) {
    Preconditions.checkNotNull(host);//from  www .  j av a 2  s  .c  om

    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);

    try {
        final Connection connection = factory.newConnection();

        this.channel = connection.createChannel();
        this.channel.exchangeDeclare(topic, "topic", durable);
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }

    // To declare a queue
    //channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    this.histogram = Histograms.create();
    this.topic = Preconditions.checkNotNull(topic);
    this.message = Preconditions.checkNotNull(message);
    this.numberOfMessagesToProduce = Preconditions.checkNotNull(numberOfMessagesToProduce);
}

From source file:blocker.Blocker.java

/**
 * @param argv/*from ww w. ja  va 2  s. com*/
 */
public static void main(String[] argv) throws Exception {
    seconds = Integer.parseInt(argv[7]);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(argv[0]);
    factory.setUsername(argv[2]);
    factory.setPassword(argv[3]);
    factory.setVirtualHost(argv[1]);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(argv[4], "direct", true);
    String queueName = channel.queueDeclare(argv[5], true, false, false, null).getQueue();

    //                          exchange  key
    channel.queueBind(queueName, argv[4], argv[6]);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            JSONParser parser = new JSONParser();

            Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread th, Throwable ex) {
                    System.out.println("Uncaught exception: " + ex);
                }
            };

            try {
                Object obj = parser.parse(message);
                JSONObject jobj = (JSONObject) obj;
                String IP = (String) jobj.get("clientip");
                Thread t = new Thread(new BlockerThread(IP));
                t.setUncaughtExceptionHandler(h);
                t.start();
            } catch (ParseException ex) {
                Logger.getLogger(Blocker.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    };
    channel.basicConsume(argv[5], true, consumer);
}

From source file:brooklyn.entity.messaging.rabbit.RabbitEc2LiveTest.java

License:Apache License

private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception {
    String uri = rabbit.getAttribute(MessageBroker.BROKER_URL);
    LOG.warn("connecting to rabbit {}", uri);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(uri);//w  ww  .ja  va  2  s  .  co m
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    return channel;
}

From source file:brooklyn.entity.messaging.rabbit.RabbitIntegrationTest.java

License:Apache License

private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception {
    String uri = rabbit.getAttribute(MessageBroker.BROKER_URL);
    log.warn("connecting to rabbit {}", uri);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(uri);/*from   ww w .  j  a  v a  2  s  .c  o m*/
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    return channel;
}