Example usage for com.rabbitmq.client ConnectionFactory newConnection

List of usage examples for com.rabbitmq.client ConnectionFactory newConnection

Introduction

In this page you can find the example usage for com.rabbitmq.client ConnectionFactory newConnection.

Prototype

public Connection newConnection() throws IOException, TimeoutException 

Source Link

Document

Create a new broker connection.

Usage

From source file:es.devcircus.rabbitmq_examples.rabbitmq_work_queues.Worker.java

License:Open Source License

/**
 * /* w w w.  j  ava2s.co m*/
 * @param argv
 * @throws Exception 
 */
public static void main(String[] argv) throws Exception {

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

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());

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

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

From source file:eu.betaas.rabbitmq.subscriber.SubscriberService.java

License:Apache License

public void startService() {
    try {//  w  ww.jav a2 s .c om
        log.info("#Starting queue #");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection;
        log.info("#Starting #");
        connection = factory.newConnection();
        log.info("#Starting connection#");
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(ename, mode);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ename, bussubkey);
        log.info("#Starting connection on queue #");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        log.info("#Running #");
        run();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ShutdownSignalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ConsumerCancelledException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.europeana.servicebus.client.rabbitmq.RabbitMQClientAsync.java

/**
 * RabbitMQ implementation of ESBClient//from www  .j ava  2  s  . co m
 *
 * @param host The host to connect to
 * @param incomingQueue The incoming queue
 * @param outgoingQueue The outgoing queue
 * @param username Username
 * @param password Password
 * @param consumer The consumer implementation - It can be null. It allows asynchronous consumers as well as enables
 * custom behaviour handling upon incoming message. The default message handling is and should be agnostic of the
 * method semantics to be implemented
 * @throws IOException
 */
public RabbitMQClientAsync(String host, String incomingQueue, String outgoingQueue, String username,
        String password, Consumer consumer) throws IOException {
    this.host = host;
    this.incomingQueue = incomingQueue;
    this.outgoingQueue = outgoingQueue;
    this.username = username;
    this.password = password;
    if (consumer == null) {
        this.consumer = new DefaultConsumer(receiveChannel);
    } else {
        this.consumer = consumer;
    }
    ConnectionFactory factory = new ConnectionFactory();
    builder = new AMQP.BasicProperties.Builder();
    factory.setHost(host);
    factory.setUsername(username);
    factory.setPassword(password);

    connection = factory.newConnection();
    sendChannel = connection.createChannel();
    receiveChannel = connection.createChannel();
    sendChannel.queueDeclare(outgoingQueue, true, false, false, null);
    receiveChannel.queueDeclare(incomingQueue, true, false, false, null);
    receiveChannel.basicConsume(incomingQueue, true, consumer);

}

From source file:eu.netide.util.topology.update.impl.NotificationProducer.java

License:Open Source License

public void init(String rabbitHost, int rabbitPort, String rabbitUser, String rabbitPassword,
        String rabbitVirtualHost, String exchangeName, String baseTopicName, String nodeTopicName,
        String nodeConnectorTopicName, String linkTopicName) {

    this.exchangeName = exchangeName;
    this.baseTopicName = baseTopicName;
    this.nodeTopicName = nodeTopicName;
    this.nodeConnectorTopicName = nodeConnectorTopicName;
    this.linkTopicName = linkTopicName;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rabbitUser);/*from   ww w  . jav a2s  .  co m*/
    factory.setPassword(rabbitPassword);
    factory.setVirtualHost(rabbitVirtualHost);
    factory.setHost(rabbitHost);
    factory.setPort(rabbitPort);
    factory.setAutomaticRecoveryEnabled(true);

    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        init = true;
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } catch (TimeoutException e) {
        LOG.error(e.getMessage());
    }
}

From source file:flens.Agent.java

License:Apache License

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

    ConfigHandler ch = new ConfigHandler();

    Gson g = new Gson();

    Map<String, Object> myconfig = g.fromJson(new FileReader(args[0]), HashMap.class);

    Map<String, String> tags = (Map<String, String>) myconfig.get("tags");

    Map<String, Object> initial = (Map<String, Object>) myconfig.get("init");

    String server = (String) myconfig.get("server");
    String name = (String) myconfig.get("name");

    System.out.println(String.format("connecting to %s as %s, with tags %s", server, name, tags));

    List<CommandHandler> chs = new LinkedList<>();
    chs.add(new PingHandler());
    chs.add(ch);/*from   ww  w  .j  a v a  2  s.  c om*/

    ConnectionFactory c = new ConnectionFactory();
    c.setHost(server);
    c.setUsername("guest");
    c.setPassword("guest");
    c.setPort(5672);

    CommandServer cs = new CommandServer(name, c.newConnection(), tags, chs);
    cs.start();
    ch.load(initial);
    ch.getEngine().addTags(tags);
    ch.getEngine().start();
}

From source file:flink.streamer.CustomRMQSource.java

License:Apache License

/**
 * Initializes the connection to RMQ./*from  w  ww .j a v a2s. c  om*/
 */
private void initializeConnection() {
    ConnectionFactory factory = setupConnectionFactory();
    try {
        factory.setUri(uri);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
        consumer = new QueueingConsumer(channel);

        RuntimeContext runtimeContext = getRuntimeContext();
        if (runtimeContext instanceof StreamingRuntimeContext
                && ((StreamingRuntimeContext) runtimeContext).isCheckpointingEnabled()) {
            autoAck = false;
            // enables transaction mode
            channel.txSelect();
        } else {
            autoAck = true;
        }

        LOG.debug("Starting RabbitMQ source with autoAck status: " + autoAck);
        channel.basicConsume(queueName, autoAck, consumer);

    } catch (IOException e) {
        throw new RuntimeException("Cannot create RMQ connection with " + queueName + " at " + uri, e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:gash.router.server.MessageServer.java

License:Apache License

public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException,
        InterruptedException, SQLException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare("inbound_queue", false, false, false, null);
    channel.basicQos(1);// w  w w  . jav  a2  s  . c o  m
    postgre = new PostgreSQL(url, username, password, dbname, ssl);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume("inbound_queue", false, consumer);
    //       Map<String, byte[]> map = new HashMap<String, byte[]>();
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        String request = props.getType();
        System.out.println(request);

        if (request != null) {
            if (request.equals("get")) {
                String key = new String(delivery.getBody());
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();
                byte[] image = postgre.get(key);
                channel.basicPublish("", props.getReplyTo(), replyProps, image);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }

            if (request.equals("put")) {
                byte[] image = delivery.getBody();
                postgre.put(props.getUserId(), image);
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();

                channel.basicPublish("", props.getReplyTo(), replyProps, image);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            if (request.equals("post")) {
                System.out.println("Message Server");
                String key = postgre.post(delivery.getBody());
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();

                channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            if (request.equals("delete")) {
                String key = new String(delivery.getBody());
                postgre.delete(key);
            }

        }
    }
}

From source file:getbanks2.GetBanks2.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException// ww  w . j  a v  a2s  .  c o  m
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel listeningChannel = connection.createChannel();
    Channel sendingChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            String banks = getBanks(arr[0], Integer.parseInt(arr[1]), Double.parseDouble(arr[2]),
                    Integer.parseInt(arr[3]));

            message += "," + banks;

            System.out.println(message);

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);
            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());

        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}

From source file:getcreditscore.GetCreditScore.java

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");

    Connection connection = factory.newConnection();
    Channel sendingChannel = connection.createChannel();
    Channel listeningChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override//from  w  w  w  . j  av a 2s.  c om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);

            String message = arr[0] + "," + creditScore(arr[0]) + "," + arr[1] + "," + arr[2];

            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");

        }
    };

    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);
}

From source file:grnet.com.entry.Actions.java

License:Open Source License

private void logRepo(Repository repo, String status) {
    StringBuffer buffer = new StringBuffer();

    buffer.append(repo.getName());/*from www  .  j  a va2  s.co  m*/
    buffer.append(" " + status);
    buffer.append(" " + repo.getUrl());
    buffer.append(" " + repo.getPrefix());
    buffer.append(" " + repo.getOaiVersion());
    buffer.append(" " + repo.getDelPolicy());
    buffer.append(" " + repo.getGranularity());
    buffer.append(" " + repo.getResponsible());
    slf4jLogger.info(buffer.toString());

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost(props.getProperty(Constants.queueHost));
    factory.setUsername(props.getProperty(Constants.queueUser));
    factory.setPassword(props.getProperty(Constants.queuePass));

    Connection connection;
    try {
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        channel.basicPublish("", QUEUE_NAME, null, buffer.toString().getBytes());
        channel.close();
        connection.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}