Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

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

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

From source file:edu.indiana.d2i.sead.matchmaker.service.messaging.Sender.java

License:Apache License

public Sender(MessagingConfig msgconf, MessagingOperationTypes OpType) throws IOException {
    this.factory = new ConnectionFactory();
    this.factory.setUsername(msgconf.getUsername());
    this.factory.setPassword(msgconf.getPassword());
    this.factory.setVirtualHost(msgconf.getVirtualHost());
    this.factory.setHost(msgconf.getHost());
    this.factory.setPort(msgconf.getPort());
    this.conn = this.factory.newConnection();
    this.channel = this.conn.createChannel();

    switch (OpType) {
    case SEND_ASYNC_REQUEST:
        this.ExchangeName = msgconf.getAsyncRequestExchangeName();
        this.RoutingKey = msgconf.getAsyncRequestRoutingKey();
        break;// ww w  .j a  va2  s  . com
    case SEND_REQUEST:
        this.ExchangeName = msgconf.getRequestExchangeName();
        this.RoutingKey = msgconf.getRequestRoutingKey();
        break;
    case SEND_RESPONSE:
        this.ExchangeName = msgconf.getResponseExchangeName();
        this.RoutingKey = msgconf.getResponseRoutingKey();
        break;
    default:
        try {
            throw new Exception("OperationType: " + OpType.toString() + " not supported.");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;
    }

}

From source file:edu.iu.messaging.service.core.impl.RabbitMQPublisher.java

License:Apache License

private void connect() {
    try {//w w  w .  j  a va2  s . c o m
        logger.info("connect() -> Connecting to server");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });

        channel = connection.createChannel();

        /*
        Not required for work queue implementation
         */
        //channel.basicQos(properties.getPrefetchCount());
        //channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true);

    } catch (Exception e) {
        logger.error("connect() -> Error connecting to server.", e);
    }

}

From source file:edu.iu.messaging.service.core.impl.RabbitMQSubscriber.java

License:Apache License

private void createConnection() {
    try {//from ww  w  . j a  v a 2  s .c  o m
        logger.info("createConnection() -> Connecting to server");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        addShutdownListener();
        channel = connection.createChannel();

        /*
        Not required for work queue implementation
         */
        //channel.basicQos(Constants.PREFETCH_COUT);
        //channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true);

    } catch (Exception e) {
        logger.error("createConnection() -> Error connecting to server.", e);
    }
}

From source file:edu.kit.dama.mdm.audit.impl.RabbitMQPublisher.java

License:Apache License

@Override
public boolean initialize() {
    boolean result = false;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);//w w  w.  j  av  a  2  s . co m
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        LOGGER.debug("Declaring exchange of type 'topic' in publisher.");
        channel.exchangeDeclare(exchangeName, "topic", true, false, false, null);
        LOGGER.debug("Declaring queue.");
        String queueName = channel.queueDeclare().getQueue();
        LOGGER.debug("Binding queue with name {} to exchange.", queueName);
        channel.queueBind(queueName, exchangeName, "");
        result = true;
    } catch (IOException | TimeoutException ex) {
        LOGGER.error("Failed to initialize RabbitMQPublisher.", ex);
    }
    return result;
}

From source file:edu.kit.dama.mdm.audit.servlet.RabbitMQInitializerListener.java

License:Apache License

@Override
public void contextInitialized(ServletContextEvent sce) {
    loadConfiguration();/*from   w  w w  .  j  a v  a2s . c o  m*/

    if (!CONFIGURED) {
        LOGGER.warn("Skipping initialization of RabbitMQ consumer.");
        return;
    }

    try {
        LOGGER.debug("Intitializing RabbitMQ consumer.");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostname);
        connection = factory.newConnection();
        channel = connection.createChannel();
        LOGGER.debug("Declaring topic based exchange with name '{}'", exchange);
        channel.exchangeDeclare(exchange, "topic", true);
        String queueName = channel.queueDeclare().getQueue();
        LOGGER.debug("Using queue with name '{}'. Binding queue to exchange.", queueName);
        channel.queueBind(queueName, exchange, "audit.*");
        LOGGER.debug("Queue bound to exchange with filter 'audit.*'. Starting consumer.");

        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");
                try {
                    LOGGER.debug("Handling new audit event.");
                    AuditEvent event = AuditEvent.fromJson(message);
                    LOGGER.debug("Submitting event to attached consumers.");
                    for (AbstractAuditConsumer consumer : AuditManager.getInstance().getConsumers()) {
                        consumer.consume(event);
                    }
                    LOGGER.debug("Event submitted to all consumers.");
                } catch (FormatException ex) {
                    LOGGER.error("Failed to consume audit event from message '" + message + "'", ex);
                }
            }
        };
        channel.basicConsume(queueName, true, consumer);
        LOGGER.debug("RabbitMQ consumer successfully initialized.");
    } catch (IOException | TimeoutException ex) {
        LOGGER.error("Failed to initialize RabbitMQ audit distributor.", ex);
    }
}

From source file:edu.kit.dama.util.test.RabbitMQReceiver.java

License:Apache License

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

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

    channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "audit.*");

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

    /*  final Consumer consumer = new DefaultConsumer(channel) {
    @Override//  www  .  java2s. c om
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    String message = new String(body, "UTF-8");
            
    System.out.println(" [x] Received '" + message + "'");
    try {
      doWork(message);
    } finally {
      System.out.println(" [x] Done");
      channel.basicAck(envelope.getDeliveryTag(), false);
    }
    }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
    }*/
    /*   QueueingConsumer consumer = new QueueingConsumer(channel);
            
           /*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");
        System.out.println(" [x] Received '" + message + "'");
    }
           };*/
    /*channel.basicConsume(queueName, true, consumer);
           QueueingConsumer.Delivery delivery = consumer.nextDelivery(10000);
           if (delivery != null) {
    byte[] message = delivery.getBody();
    System.out.println("MESS " + new String(message));
           }*/
    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");
            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);

    // System.exit(0);
}

From source file:edu.kit.dama.util.test.RabbitMQTest.java

License:Apache License

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

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true, false, false, null);
    //channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    /*String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");*/

    String message = "Hello!";

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

    channel.close();// w  ww  .  j  a  v a  2 s. co m
    connection.close();

}

From source file:EncoderHealthEstimator.EncoderHealthEstimatorImplAbstract.java

License:Open Source License

public EncoderHealthEstimatorImplAbstract() {

    mLogger = Logger.getLogger("EncoderHealthEstimator");
    PropertyConfigurator.configure("log4j.properties");

    try {/*from  w w w  . j  a  va2 s  . c o  m*/
        mFactory = new ConnectionFactory();
        mFactory.setHost("localhost");
        mConnection = mFactory.newConnection();
        mChannel = mConnection.createChannel();

        /*
         * Defines that messages in this queue are persistent (i.e. to be saved on disk)    
         * so that even if RabbitMQ server quits the messages is not lost.
         * Note that when publishing a message, the msg itself has to be declared persistent.
         */
        boolean durable = false; // for commands we don't want it!

        /*
         * true if the server should consider messages acknowledged once delivered; 
         * false if the server should expect explicit acknowledgements.
         */
        boolean autoAck = true;

        // command queue      
        boolean exclusive = false; // restricted to this connection
        boolean autoDelete = false; // server will delete the queue when no longer in use
        mChannel.queueDeclare(CMD_QUEUE_NAME, durable, exclusive, autoDelete, null);

        // broadcasted commands (don't need to subscribe to a topic)
        mChannel.exchangeDeclare(CMD_EXCHANGE_NAME, "fanout", durable);
        String cmdFanoutQueueName = mChannel.queueDeclare().getQueue();
        mChannel.queueBind(cmdFanoutQueueName, CMD_EXCHANGE_NAME, "");

        // data topics to subscribe
        durable = true; // for data we want persistance!
        mChannel.exchangeDeclare(DATA_EXCHANGE_NAME, "topic", durable);
        String dataPubsubQueueName = mChannel.queueDeclare().getQueue();
        mChannel.queueBind(dataPubsubQueueName, DATA_EXCHANGE_NAME, "GetEncHealthFlag");

        // define which queues to get the messages from 
        mConsumer = new QueueingConsumer(mChannel);
        mChannel.basicConsume(CMD_QUEUE_NAME, autoAck, mConsumer);
        mChannel.basicConsume(cmdFanoutQueueName, autoAck, mConsumer);
        mChannel.basicConsume(dataPubsubQueueName, autoAck, mConsumer);

    } catch (IOException e) {
        mLogger.error("Could not create RMQ channel: " + e.getMessage());
        return;
    }

    try {
        mEngine = new SMEngine(mLogger, SMJavaInvoker.class);
        // The context has to be created before the actions/activities are executed
        mEngine.setContextVar("CHANNEL", mChannel);
        mEngine.setContextVar("CMD_QUEUE_NAME", CMD_QUEUE_NAME);
        mEngine.setContextVar("CMD_EXCHANGE_NAME", CMD_EXCHANGE_NAME);
        mEngine.setContextVar("DATA_EXCHANGE_NAME", DATA_EXCHANGE_NAME);
        mEngine.loadModel("EncoderHealthEstimator.xml");
        mEngine.startExecution();
    } catch (IOException e) {
        mLogger.error("Could not start SM execution: " + e.getMessage());
        return;
    }

    mIsRunning = true;
}

From source file:EncoderHealthEstimator.SMActivity.java

License:Open Source License

public void openConnection() {
    try {//  www .  j av  a2  s  .  co m
        boolean durable = true; // for data we want persistance
        boolean autoAck = true;

        mFactory = new ConnectionFactory();
        mFactory.setHost("localhost");
        mConnection = mFactory.newConnection();
        mChannel = mConnection.createChannel();

        // data pub/sub
        mChannel.exchangeDeclare(DATA_EXCHANGE_NAME, "topic", durable);
        String pubsubQueueName = mChannel.queueDeclare().getQueue();

        mChannel.queueBind(pubsubQueueName, DATA_EXCHANGE_NAME, "GetEncHealthFlag");

        mConsumer = new QueueingConsumer(mChannel);
        mChannel.basicConsume(pubsubQueueName, autoAck, mConsumer);

    } catch (IOException e) {
        getLogger().error("Could not create RMQ channel: " + e.getMessage());
        stopRunning();
    }
}

From source file:es.devcircus.rabbitmq_examples.rabbitmq_hello_world.Recv.java

License:Open Source License

/**
 * //from   w w  w. j a v  a  2 s  . 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(QUEUE_NAME, false, false, false, null);
    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 + "'");
    }
}