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:com.shopwiki.roger.rpc.RpcServer.java

License:Apache License

/**
 * 1. Creates {@link RpcWorker}s using the {@link WorkerFactory} provided to the constructor.
 * 2. Declares queues & binds routing-keys if a (@link QueueDeclarator} was provided to the constructor.
 * 3. Starts each {@link RpcWorker}./*from   w w  w. ja va  2s.com*/
 *
 * @throws IOException
 */
public void start() throws IOException {
    RpcWorkers workers = workerFactory.createWorkers(queuePrefix);

    Connection conn = null;
    try {
        conn = workers.getConnection();
        conn.addShutdownListener(reconnector);
        Channel channel = conn.createChannel();

        if (queueDeclarator != null) {
            for (RpcWorker worker : workers) {
                queueDeclarator.declareQueue(channel, worker);
                queueDeclarator.bindQueue(channel, worker);
            }
        }

        for (RpcWorker worker : workers) {
            worker.setPostProcessors(postProcessors);
            String queueName = worker.getQueueName();

            System.out.println(channel + " - Starting Worker for queue: " + queueName);
            channel.queueDeclarePassive(queueName); // make sure the handler's queue exists
            worker.start();
        }
    } catch (IOException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (RuntimeException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (Error e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    }
}

From source file:com.simple.sftpfetch.publish.RabbitClient.java

License:Apache License

/**
 * Initialize the RabbitClient, establish a connection and declare the exchange
 *
 * @param factory the RabbitMQ ConnectionFactory
 * @param connectionInfo a bean containing the necessary connection information
 *
 * @throws NoSuchAlgorithmException//  w  w w .  j  av  a  2s .  c o m
 * @throws KeyManagementException
 * @throws URISyntaxException
 * @throws IOException
 */
public RabbitClient(ConnectionFactory factory, RabbitConnectionInfo connectionInfo)
        throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException {
    factory.setHost(connectionInfo.getHostname());
    factory.setPort(connectionInfo.getPort());
    factory.setUsername(connectionInfo.getUsername());
    factory.setPassword(connectionInfo.getPassword());
    factory.setVirtualHost(connectionInfo.getVhost());
    factory.setConnectionTimeout(connectionInfo.getTimeout());
    Connection conn = factory.newConnection();
    exchange = connectionInfo.getExchange();
    channel = conn.createChannel();
    channel.exchangeDeclare(exchange, EXCHANGE_TYPE, true);
    this.amqpProperties = new AMQP.BasicProperties.Builder().contentType(CONTENT_TYPE).deliveryMode(2).build();
}

From source file:com.sitewhere.protobuf.test.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "SITEWHERE.IN";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672/SITEWHERE.IN");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = generateEncodedMeasurementsMessage();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();//from  w w  w.j  a v a2s . c om
    connection.close();
}

From source file:com.sitewhere.sources.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "sitewhere.input";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = EventsHelper.generateEncodedMeasurementsMessage(HARDWARE_ID);
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();//  w  w w. j  a  va2 s  .co m
    connection.close();
}

From source file:com.siva.rabbitmq.AmqpMsgPublisher.java

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setUsername("admin");
    factory.setPassword("welcome01");
    factory.setPort(5672);// w ww.j  a  v  a  2 s. c o  m
    factory.setVirtualHost("/admin_vhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    String routingKey = "mqtt_topic.iot.admin_vhost";
    String message = "Test Message from IoT";

    channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
    System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

    connection.close();
}

From source file:com.trivago.mail.pigeon.daemon.Daemon.java

License:Apache License

/**
 * Main Daemon method containing the event loop.
 *
 * @param args command line args//from  ww  w .  j  a va  2 s. c  o  m
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {

    Connection conn = null;
    Channel channel = null;

    try {
        conn = ConnectionPool.getConnection();
        channel = conn.createChannel();

        boolean autoAck = false;
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(channelName, autoAck, consumer);
        MailFacade mailFacade = new MailFacade();

        while (true) {
            QueueingConsumer.Delivery delivery;
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException ie) {
                continue;
            }

            String jsonContent = new String(delivery.getBody());
            MailTransport mailTransport = JSONParser.defaultJSONParser().parse(MailTransport.class,
                    jsonContent);
            mailFacade.sendMail(mailTransport);
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

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

From source file:com.trivago.mail.pigeon.web.data.process.QueueNewsletter.java

License:Apache License

private void queueNewsletter(Mail mail, Sender sender, Recipient recipient, Campaign campaign) {
    Connection conn = ConnectionPool.getConnection();
    Channel channel = null;//from   w w w.java 2 s . c om
    MailTransport transport = templateProcessor.processMail(mail, recipient, sender, campaign);

    if (transport == null) {
        log.warn(
                "Template processor returned null instead of a mail transport object. This is probably a bug!");
        return;
    }

    if (transport.shouldAbortSending() && !transport.shouldEnforceSending()) {
        log.info("Skipped mail to " + transport.getTo() + " because transport aborted sending.");
        return;
    }

    String json = JSON.defaultJSON().forValue(transport);

    try {
        channel = conn.createChannel();
        channel.exchangeDeclare("mailpidgeon", "direct", true);
        channel.queueDeclare(channelName, true, false, false, null);
        channel.queueBind(channelName, "mailpidgeon", "mailpidgeon");

        byte[] messageBodyBytes = json.getBytes();
        channel.basicPublish("mailpidgeon", "mailpidgeon", null, messageBodyBytes);

    } catch (IOException e) {
        log.error(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                log.error("Could not close channel", e);
            }
        }
    }
}

From source file:com.trivago.mail.pigeon.web.data.process.QueueNewsletter.java

License:Apache License

public int getProgress(long newsletterId) {
    Connection conn = ConnectionPool.getConnection();
    Channel channel = null;//from w ww .  j  ava2 s  .co m
    try {
        channel = conn.createChannel();
        AMQP.Queue.DeclareOk declareOk = channel.queueDeclarePassive(channelName);
        return declareOk.getMessageCount();
    } catch (Exception e) {
        log.error("Error while fetching progress", e);
    } finally {
        assert channel != null;
        try {
            channel.close();
        } catch (IOException e) {
            log.error("Could not close channel", e);
        }
    }
    return 0;
}

From source file:com.UseCaseSimpleConsumer.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {/*from   w  w  w .  ja v  a  2  s  .  c o  m*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }
    try {
        channel.queueDeclarePassive(ROUTE_KEY);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(ROUTE_KEY, false, false, false, null);
    }

    channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY);

    String param = "IBM";
    String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n"
            + "        <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + "        <m:quantity>"
            + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + "        <m:symbol>" + param
            + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>";

    channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY,
            new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes());
    System.out.println(" [x] Sent '" + msg + "'");
    channel.close();
    connection.close();
}

From source file:com.UseCaseSimpleProducer.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException, InterruptedException {

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

    try {//from   w w  w .  j a  v a2s .  c  o  m
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
    }
}