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:net.roboconf.messaging.internal.client.rabbitmq.RabbitMqClientAgent.java

License:Apache License

@Override
public void openConnection() throws IOException {

    // Already connected? Do nothing
    this.logger.info("Agent '" + getAgentId() + "' is opening a connection to RabbitMQ.");
    if (this.channel != null) {
        this.logger.info("Agent '" + getAgentId() + "' has already a connection to RabbitMQ.");
        return;//from www. j  a  v a  2s .  co  m
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.messageServerUsername,
            this.messageServerPassword);
    this.channel = factory.newConnection().createChannel();
    this.logger.info("Agent '" + getAgentId() + "' established a new connection with RabbitMQ. Channel # "
            + this.channel.getChannelNumber());

    // We start listening the queue here
    // We declare both exchanges.
    // This is for cases where the agent would try to contact the DM
    // before the DM was started. In such cases, the RabbitMQ client
    // will get an error. This error will in turn close the channel and it
    // won't be usable anymore.
    RabbitMqUtils.declareApplicationExchanges(this.applicationName, this.channel);
    // This is really important.

    // Queue declaration is idem-potent
    String queueName = getQueueName();
    this.channel.queueDeclare(queueName, true, false, true, null);

    // Start to listen to the queue
    final QueueingConsumer consumer = new QueueingConsumer(this.channel);
    this.consumerTag = this.channel.basicConsume(queueName, true, consumer);

    String threadName = "Roboconf - Queue listener for Agent " + this.rootInstanceName;
    String id = "Agent '" + getAgentId() + "'";
    new ListeningThread(threadName, this.logger, consumer, this.messageQueue, id).start();
}

From source file:net.roboconf.messaging.internal.client.rabbitmq.RabbitMqClientDm.java

License:Apache License

@Override
public void openConnection() throws IOException {

    // Already connected? Do nothing
    this.logger.info("The DM is opening a connection to RabbitMQ.");
    if (isConnected()) {
        this.logger.info("The DM has already a connection to RabbitMQ.");
        return;//from ww  w  .  j av  a2s  .  c om
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.messageServerUsername,
            this.messageServerPassword);
    this.channel = factory.newConnection().createChannel();
    this.logger.info(
            "The DM established a new connection with RabbitMQ. Channel # " + this.channel.getChannelNumber());

    // Be notified when a message does not arrive in a queue (i.e. nobody is listening)
    this.channel.addReturnListener(new DmReturnListener());

    // Declare the DM debug-dedicated queue.
    this.channel.queueDeclare(DM_NEUTRAL_QUEUE_NAME, true, false, true, null);

    // Start listening to messages.
    this.consumer = new QueueingConsumer(this.channel);
    String threadName = "Roboconf - Queue listener for the DM";
    String id = "The DM";
    new ListeningThread(threadName, this.logger, this.consumer, this.messageQueue, id).start();
}

From source file:net.roboconf.messaging.internal.RabbitMqTestUtils.java

License:Apache License

/**
 * Creates a channel to interact with a RabbitMQ server for tests.
 * @return a non-null channel/*  w w w .j a va 2  s .  c  o  m*/
 * @throws IOException if the creation failed
 */
public static Channel createTestChannel() throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(MESSAGE_SERVER_IP);
    Channel channel = factory.newConnection().createChannel();

    return channel;
}

From source file:net.roboconf.messaging.rabbitmq.internal.RabbitMqClient.java

License:Apache License

@Override
public void openConnection() throws IOException {

    // Already connected? Do nothing
    this.logger.info(getId() + " is opening a connection to RabbitMQ.");
    if (isConnected()) {
        this.logger.info(getId() + " has already a connection to RabbitMQ.");
        return;// w  w  w.j  a va  2 s .c om
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.configuration);
    this.channel = factory.newConnection().createChannel();
    this.logger.info(getId() + " established a new connection with RabbitMQ. Channel # "
            + this.channel.getChannelNumber());

    // Be notified when a message does not arrive in a queue (i.e. nobody is listening)
    this.channel.addReturnListener(new RoboconfReturnListener());

    // Add a recoverable listener (when broken connections are recovered).
    // Given the way the RabbitMQ factory is configured, the channel should be "recoverable".
    ((Recoverable) this.channel).addRecoveryListener(new RoboconfRecoveryListener());

    // Declare the exchanges.
    RabbitMqUtils.declareGlobalExchanges(this.domain, this.channel);
    RabbitMqUtils.declareApplicationExchanges(this.domain, this.applicationName, this.channel);

    // Declare the dedicated queue.
    String queueName = getQueueName();
    this.channel.queueDeclare(queueName, true, false, true, null);

    // Start listening to messages.
    RoboconfConsumer consumer = new RoboconfConsumer(getId(), this.channel, this.messageQueue);
    consumer.handleConsumeOk(queueName);
    this.consumerTag = this.channel.basicConsume(queueName, true, consumer);
    this.logger.finer("A new consumer tag was created: " + this.consumerTag);
}

From source file:net.roboconf.messaging.rabbitmq.internal.utils.RabbitMqTestUtils.java

License:Apache License

/**
 * Creates a channel to interact with a RabbitMQ server for tests.
 * @param messageServerIp the message server's IP address
 * @param username the user name for the messaging server
 * @param password the password for the messaging server
 * @return a non-null channel// w w  w .  j  a  v a  2s  .c o m
 * @throws IOException if the creation failed
 */
public static Channel createTestChannel(String messageServerIp, String username, String password)
        throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(messageServerIp);
    factory.setUsername(username);
    factory.setPassword(password);

    return factory.newConnection().createChannel();
}

From source file:net.yacy.grid.io.messages.RabbitQueueFactory.java

License:Open Source License

private void init() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.server);
    if (this.port > 0)
        factory.setPort(this.port);
    if (this.username != null && this.username.length() > 0)
        factory.setUsername(this.username);
    if (this.password != null && this.password.length() > 0)
        factory.setPassword(this.password);
    try {/*from  w  w  w.ja  va  2 s.com*/
        this.connection = factory.newConnection();
        this.channel = connection.createChannel();
        this.queues = new ConcurrentHashMap<>();
    } catch (TimeoutException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:nl.uva.sne.drip.api.rpc.DRIPCaller.java

License:Apache License

public DRIPCaller(String messageBrokerHost, String requestQeueName) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(messageBrokerHost);//  ww w  .  j  a v a  2s .  c o m
    factory.setPort(AMQP.PROTOCOL.PORT);
    //factory.setUsername("guest");
    //factory.setPassword("pass");

    connection = factory.newConnection();
    channel = connection.createChannel();
    // create a single callback queue per client not per requests. 
    replyQueueName = channel.queueDeclare().getQueue();
    this.requestQeueName = requestQeueName;
    this.mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
}

From source file:nl.uva.sne.drip.drip.component_example.RPCServer.java

License:Apache License

private static void start() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);//from ww w.j  a  v  a2  s.c  om
    factory.setPassword("guest");
    factory.setUsername("guest");
    factory.setPort(AMQP.PROTOCOL.PORT);
    try (Connection connection = factory.newConnection()) {
        Channel channel = connection.createChannel();
        //We define the queue name 
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        //Set our own customized consummer 
        Consumer c = new Consumer(channel);
        //Start listening for messages 
        channel.basicConsume(RPC_QUEUE_NAME, false, c);

        //Block so we don't close the channel
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException _ignore) {
            }
        }

    } catch (IOException | TimeoutException ex) {
        Logger.getLogger(RPCServer.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:nl.uva.sne.drip.drip.provisioner.RPCServer.java

License:Apache License

private static void start() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(PropertyValues.HOST);
    factory.setPassword("guest");
    factory.setUsername("guest");
    factory.setPort(AMQP.PROTOCOL.PORT);
    Logger.getLogger(RPCServer.class.getName()).log(Level.INFO, "Connected to: {0}", PropertyValues.HOST);
    try (Connection connection = factory.newConnection()) {
        Channel channel = connection.createChannel();
        //We define the queue name 
        channel.queueDeclare(PropertyValues.RPC_QUEUE_NAME, false, false, false, null);
        DefaultConsumer c;/*from ww  w. java 2  s . c o m*/
        if (PropertyValues.RPC_QUEUE_NAME.endsWith("v0")) {
            c = new nl.uva.sne.drip.drip.provisioner.v0.Consumer(channel);
        } else {
            c = new nl.uva.sne.drip.drip.provisioner.v1.Consumer(channel, PropertyValues.HOST);
        }

        //Start listening for messages 
        channel.basicConsume(PropertyValues.RPC_QUEUE_NAME, false, c);

        //Block so we don't close the channel
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException _ignore) {
            }
        }

    } catch (IOException | TimeoutException ex) {
        Logger.getLogger(RPCServer.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:OnlyPackege.TheMightyBank.java

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

    JSONParser jsonParster = new JSONParser();

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

    recvChannel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String queueName = recvChannel.queueDeclare().getQueue();
    recvChannel.queueBind(queueName, EXCHANGE_NAME, "");

    QueueingConsumer consumer = new QueueingConsumer(recvChannel);
    recvChannel.basicConsume(queueName, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String responseQueue = delivery.getProperties().getReplyTo();

        Channel sendChannel = connection.createChannel();
        sendChannel.queueDeclare(responseQueue, false, false, false, null);

        String message = new String(delivery.getBody());
        JSONObject recvObj = (JSONObject) jsonParster.parse(message);

        //to be deleted after testing
        System.out.println(" [x] Received '" + message + "'");

        JSONObject obj = new JSONObject();
        obj.put("ssn", recvObj.get("ssn"));
        obj.put("interestRate", Math.random() * 10);

        sendChannel.basicPublish("", responseQueue, null, obj.toJSONString().getBytes());
    }/*from w  ww  .  j  a  v a2  s  . c o m*/
}