Example usage for com.rabbitmq.client ConnectionFactory setRequestedHeartbeat

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

Introduction

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

Prototype

public void setRequestedHeartbeat(int requestedHeartbeat) 

Source Link

Document

Set the requested heartbeat timeout.

Usage

From source file:org.teksme.server.common.messaging.AMQPBrokerManager.java

License:Apache License

protected Connection connect(MessageMiddleware msgMiddlewareConfig) throws IOException {

    logger.info("Connecting to AMQP broker...");

    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setUsername(msgMiddlewareConfig.getUsername());
    connFactory.setPassword(msgMiddlewareConfig.getPasswd());
    connFactory.setVirtualHost(msgMiddlewareConfig.getVirtualHost());
    connFactory.setHost(msgMiddlewareConfig.getHost());
    connFactory.setRequestedHeartbeat(0);
    connFactory.setPort(/*  w  w  w. j  av a 2 s.  c o m*/
            msgMiddlewareConfig.getPort() == null ? AMQP.PROTOCOL.PORT : msgMiddlewareConfig.getPort());

    toString(connFactory);

    try {
        conn = connFactory.newConnection();
    } catch (Exception e) {
        e.printStackTrace();
    }
    conn.addShutdownListener(this);

    logger.info("RabbitMQ AMQP broker connected!");

    return conn;
}

From source file:org.trianacode.TrianaCloud.Utils.RPCClient.java

License:Open Source License

public RPCClient() {
    try {//from   w w w  . ja  va  2s .com
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("zotac.toaster.dbyz.co.uk");
        factory.setVirtualHost("trianacloud");
        factory.setUsername("trianacloud");
        factory.setPassword("trianacloud");
        factory.setRequestedHeartbeat(60);
        connection = factory.newConnection();
        channel = connection.createChannel();

        replyQueueName = channel.queueDeclare().getQueue();
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(replyQueueName, true, consumer);
    } catch (Exception e) {
        logger.fatal("Error connecting to Rabbit while initialising RPCClient", e);
    }
}

From source file:org.trpr.mule.transport.rabbitmq.RabbitConnector.java

License:Apache License

/**
 * Abstract method implementation. Creates the AMQP connection
 * @see org.mule.transport.AbstractConnector#doConnect()
 *///from w  ww  .  ja va2 s. com
protected void doConnect() throws Exception {
    if (connection == null) {
        int totalNumberOfNodes = rabbitMQConfigurations.size();
        int tries = 0;
        while (tries <= totalNumberOfNodes) {
            int index = (lastUsedConnectionIndex + 1) % totalNumberOfNodes;
            RabbitMQConfiguration rabbitMQConfiguration = null;
            try {
                ConnectionFactory factory = new ConnectionFactory();
                rabbitMQConfiguration = rabbitMQConfigurations.get(index);
                factory.setUsername(rabbitMQConfiguration.getUserName());
                factory.setPassword(rabbitMQConfiguration.getPassword());
                factory.setVirtualHost(rabbitMQConfiguration.getVirtualHost());
                factory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestHeartBeat());
                factory.setHost(rabbitMQConfiguration.getHostName());
                factory.setPort(rabbitMQConfiguration.getPortNumber());
                connection = factory.newConnection();
                lastUsedConnectionIndex = index;
                logger.info("Connection successfully created to configuration = " + rabbitMQConfiguration);
                return;
            } catch (Exception e) {
                logger.info("Failed to connect to Rabbit MQ Node. Configuration is " + rabbitMQConfiguration
                        + ". Will try other configurations");
            }
            tries++;
        }
        logger.error("Failed to connect to all configured Rabbit MQ nodes");
        throw new Exception("Failed to connect to all configured Rabbit MQ nodes");
    }
}

From source file:org.trpr.platform.integration.impl.messaging.RabbitConnectionHolder.java

License:Apache License

/**
 * Helper method to create RabbitMQ {@link Connection} and {@link Channel} for the specified {@link RabbitMQRpcConfiguration}
 * @param configuration the RabbitMQRpcConfiguration or one of its sub-types to create connection objects for
 * @throws MessagingException in case of errors during connection & channel creation
 *//*from w  w  w .  j  a va  2 s. c  o m*/
private void createConnection(RabbitMQRpcConfiguration configuration) throws MessagingException {

    synchronized (this) { // all code blocks that mutate the connection and channel objects held by this class are synchronized

        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(configuration.getUserName());
        factory.setPassword(configuration.getPassword());
        factory.setVirtualHost(configuration.getVirtualHost());
        factory.setRequestedHeartbeat(configuration.getRequestHeartBeat());
        factory.setHost(configuration.getHostName());
        factory.setPort(configuration.getPortNumber());

        try {
            // create the connection
            this.conn = factory.newConnection();
            // add a shutdown listener to the newly created connection
            this.conn.addShutdownListener(this);
            // create the channel
            this.channel = this.conn.createChannel();
            this.channel.exchangeDeclare(configuration.getExchangeName(), configuration.getExchangeType(),
                    configuration.isDurable());

        } catch (Exception e) {
            LOGGER.error("Error initializing RabbitMQ connection for : " + configuration.toString(), e);
            throw new MessagingException(
                    "Error initializing RabbitMQ connection for : " + configuration.toString()); //not passing the root cause as it is logged here
        }
    }

}

From source file:rabbitmqapp.EmitLog.java

public static void main(String... args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(Cons.RABBIT_MQ_URL);
    factory.setConnectionTimeout(3000);//from   ww  w  .j av a 2 s.c  o m
    factory.setRequestedHeartbeat(30);

    //Create a connection
    Connection connection = factory.newConnection();
    //create a channel from connection
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(Cons.EXCHANGE_NAME, EXCHANGE_TYPE);
    String message = "Hello Dolly";

    channel.basicPublish(Cons.EXCHANGE_NAME, "", null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");
    channel.close();
    connection.close();
}

From source file:rabbitmqapp.RabbitMQApp.java

/**
 * @param args the command line arguments
 *//*from  ww w.  ja va2 s.  co m*/
public static void main(String[] args) throws Exception {
    ProductOrder order = new ProductOrder("Thando Mlauzi", 34.50);
    ConnectionFactory factory = new ConnectionFactory();
    String uri = "amqp://ytsoedex:Qu2LCiBJ5x9fhRUyLYkMhJqsURJ9dkSP@chicken.rmq.cloudamqp.com/ytsoedex";
    factory.setUri(uri);

    //Recommended settings
    factory.setRequestedHeartbeat(30);
    factory.setConnectionTimeout(30000);

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

    channel.queueDeclare(QUENAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUENAME, null, RabbitUtility.convertToByteArray(order));
    System.out.println(" [x] Sent '" + order + "'");

    channel.close();
    connection.close();

}

From source file:red.yelo.chat.AbstractRabbitMQConnector.java

License:Open Source License

/**
 * Connect to the broker and create the exchange
 *
 * @return success//ww w.  ja v  a 2  s  .c o m
 */
protected boolean connectToRabbitMQ(final String userName, final String password) {
    if ((mChannel != null) && mChannel.isOpen()) {
        return true;
    }
    try {
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(mServer);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(mVirtualHost);
        connectionFactory.setPort(mPort);
        // if (AbstractYeloActivity.mainActivityIsOpen()) {
        connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT);
        Logger.d(TAG, AppConstants.HEART_BEAT + "");
        //            }
        //            else{
        //                connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT_BACKGROUND);
        //                Logger.d(TAG,AppConstants.HEART_BEAT_BACKGROUND+"");
        //
        //            }
        mConnection = connectionFactory.newConnection();
        mChannel = mConnection.createChannel();
        mChannel.exchangeDeclare(mExchange, mExchangeType.key);

        return true;
    } catch (final Exception e) {
        e.printStackTrace();

        return false;
    }
}

From source file:ss.udapi.sdk.services.MQListener.java

License:Apache License

public synchronized void assureConnectionIsOpen() throws Exception {

    if (isConnectionOpen())
        return;/*from  w  ww.  ja v a  2  s .c  o  m*/

    if (channel == null) {
        logger.debug("MQ Channel not created");
    } else {
        logger.debug("MQ Channel is open: " + channel.isOpen());
    }

    try {

        logger.debug("Opening MQ channel");

        // try {
        String path = resourceQURI.getRawPath();
        String host = resourceQURI.getHost();
        String userInfo = resourceQURI.getRawUserInfo();
        String virtualHost = uriDecode(path.substring(1, path.indexOf('/', 1)));
        int port = resourceQURI.getPort();

        // Set up the connection.
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setRequestedHeartbeat(Integer.parseInt(SystemProperties.get("ss.conn_heartbeat")));
        connectionFactory.setHost(host);
        connectionFactory.setVirtualHost("/" + virtualHost);

        userInfo = URLDecoder.decode(userInfo, "UTF-8");
        if (userInfo != null) {
            String userPass[] = userInfo.split(":");

            if (userPass.length > 2) {
                throw new Exception("Invalid user details format in AMQP URI: " + userInfo);
            }

            connectionFactory.setUsername(uriDecode(userPass[0]));
            if (userPass.length == 2) {
                connectionFactory.setPassword(uriDecode(userPass[1]));
            }
        }

        if (port != -1) {
            connectionFactory.setPort(port);
        }

        // Start up the connection
        connection = connectionFactory.newConnection();

        /*
         * And create a consumer using the first queue. This consumer allows
         * subsequent queue listeners to be added and removed as resources
         * are created / deleted.
         */
        boolean connectSuccess = false;
        for (int retries = 1; retries <= CONNECT_RETRIES; retries++) {

            logger.info("Attempting new connection to MQ...");

            try {

                channel = connection.createChannel();
                channel.basicQos(0, 10, false);
                consumer = new RabbitMqConsumer(channel);

                // Create a queue listener for the first fixture.
                connectSuccess = true;
                break;

            } catch (IOException ex) {
            }
        }

        if (connectSuccess == false) {
            throw new IOException("Failure creating channel after " + CONNECT_RETRIES + " attempts");
        }

        logger.info("Connection made to MQ");

    } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding while opening MQ connection: " + e);
        throw e;
    } catch (IOException e) {
        logger.error("IO error while opening MQ connection: " + e);
        throw e;
    } catch (Exception e) {
        logger.error("Generic error while opening MQ connection: " + e);
        throw e;
    }

}

From source file:uk.ac.soton.itinnovation.experimedia.arch.ecc.amqpAPI.impl.amqp.AMQPConnectionFactory.java

public void connectToAMQPHost() throws Exception {
    // Safety first
    if (amqpHostIP == null)
        throw new Exception("AMQP Host IP not correct");
    if (amqpConnection != null)
        throw new Exception("Already connected to host");

    ConnectionFactory amqpFactory = new ConnectionFactory();
    amqpFactory.setHost(amqpHostIP.getHostAddress());
    amqpFactory.setPort(amqpPortNumber);

    // Select login credentials (if available)
    String selUserName = "guest";
    String selPassword = "guest";

    if (userName != null && userPass != null) {
        selUserName = userName;//from  www. j a v  a  2s  .co  m
        selPassword = userPass;
    }

    // Set login details
    amqpFactory.setUsername(selUserName);
    amqpFactory.setPassword(selPassword);
    factoryLog.info("Logging into RabbitMQ as \'" + userName + "\'");

    // Set heartbeat rate, if available
    if (heartbeatRate != null)
        amqpFactory.setRequestedHeartbeat(heartbeatRate);

    // Execute log-in
    try {
        amqpConnection = amqpFactory.newConnection();
    } catch (Exception ex) {
        throw new Exception("Could not create AMQP host connection", ex);
    }
}

From source file:ws.ament.hammock.rabbitmq.ConnectionFactoryProducer.java

License:Apache License

@Produces
@ApplicationScoped/*from   w  w w  .j a va2 s.  com*/
public ConnectionFactory createConnectionFactory(RabbitMQConfiguration rabbitMQConfiguration) {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(rabbitMQConfiguration.isAutomaticRecovery());
    connectionFactory.setClientProperties(rabbitMQConfiguration.getClientProperties());
    connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeout());
    connectionFactory.setExceptionHandler(rabbitMQConfiguration.getExceptionHandler());
    connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeout());
    connectionFactory.setHeartbeatExecutor(rabbitMQConfiguration.getHeartbeatExecutor());
    connectionFactory.setMetricsCollector(rabbitMQConfiguration.getMetricsCollector());
    connectionFactory.setHost(rabbitMQConfiguration.getHost());
    connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryInterval());
    if (rabbitMQConfiguration.isNio()) {
        connectionFactory.useNio();
        connectionFactory.setNioParams(rabbitMQConfiguration.getNioParams());
    }
    connectionFactory.setPassword(rabbitMQConfiguration.getPassword());
    connectionFactory.setPort(rabbitMQConfiguration.getPort());
    connectionFactory.setRequestedChannelMax(rabbitMQConfiguration.getRequestedChannelMax());
    connectionFactory.setRequestedFrameMax(rabbitMQConfiguration.getRequestedFrameMax());
    connectionFactory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestedHeartbeat());
    connectionFactory.setSaslConfig(rabbitMQConfiguration.getSaslConfig());
    connectionFactory.setSharedExecutor(rabbitMQConfiguration.getSharedExecutor());
    connectionFactory.setShutdownExecutor(rabbitMQConfiguration.getShutdownExecutor());
    connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeout());
    connectionFactory.setSocketConfigurator(rabbitMQConfiguration.getSocketConf());
    connectionFactory.setSocketFactory(rabbitMQConfiguration.getFactory());
    connectionFactory.setThreadFactory(rabbitMQConfiguration.getThreadFactory());
    connectionFactory.setTopologyRecoveryEnabled(rabbitMQConfiguration.isTopologyRecovery());
    try {
        connectionFactory.setUri(rabbitMQConfiguration.getUri());
    } catch (Exception e) {
        throw new RuntimeException("Unable to populate URI ", e);
    }
    connectionFactory.setUsername(rabbitMQConfiguration.getUsername());
    connectionFactory.setVirtualHost(rabbitMQConfiguration.getVirtualHost());
    if (rabbitMQConfiguration.getSslContext() != null) {
        connectionFactory.useSslProtocol(rabbitMQConfiguration.getSslContext());
    }
    return connectionFactory;
}