Example usage for com.rabbitmq.client ConnectionFactory setConnectionTimeout

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

Introduction

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

Prototype

public void setConnectionTimeout(int timeout) 

Source Link

Document

Set the TCP connection timeout.

Usage

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);
    factory.setRequestedHeartbeat(30);/*from ww w  .jav  a  2s  . co  m*/

    //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 w w w .  jav a2  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:tracer.manager.Manager.java

License:Apache License

public void connectToRabbitNode() {
    try {//from  w  ww.  j  a  va 2s . c o  m
        com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory();
        myFactory.setHost(HOST);
        myFactory.setPort(PORT);
        myFactory.setUsername(USER_NAME);
        myFactory.setPassword(PASSWORD);
        myFactory.setVirtualHost(VIRTUAL_HOST_NAME);
        myFactory.setConnectionTimeout(TIMEOUT);

        //Automatic recovery from network failures
        myFactory.setAutomaticRecoveryEnabled(true);
        System.out.println("automatic recovery from network failures is " + "enabled");

        System.out.println("creating new connection..");
        myConnection = myFactory.newConnection();

        System.out.println("host: " + HOST + " is connected..");

        System.out.println("creating new channel..");
        myChannel = myConnection.createChannel();
        System.out.println("declaring new Exchange..");

        switch (getExchageParams()) {
        case 0:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, false, null);
            break;
        case 1:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, false, null);
            break;
        case 2:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, false, null);
            break;
        case 3:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, false, true, null);
            break;
        case 4:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, false, null);
            break;
        case 5:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, true, null);
            break;
        case 6:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, false, true, true, null);
            break;
        case 7:
            myChannel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, true, true, null);
            break;
        default:
            break;
        }
        System.out.println("creating random queue..");
        String QUEUE_NAME = myChannel.queueDeclare().getQueue();
        for (String bindingKey : BINDING_KEYS) {
            System.out.println("binding to exchange=" + EXCHANGE_NAME + " using Binding Key=" + bindingKey);
            myChannel.queueBind(QUEUE_NAME, EXCHANGE_NAME, bindingKey);
        }
        System.out.println("waiting for messages, this may take few seconds" + "..");
        System.out.println(" - rk: routing key");
        System.out.println(" - en: exchange name");
        System.out.println(" - ts: time stamp");
        System.out.println(" - ct: content type");
        System.out.println(" - ce: content encoding");
        System.out.println(" - mp: message preview");
        myStatsUpdater.start();
        com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) {
            int messageCounter = 1;

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                String messageCore = new String(body, "UTF-8");
                String currentRoutingKey = envelope.getRoutingKey();
                //currentRPC is used for display in the global tracing table
                String currentRPC = getRPCMethod(messageCore);
                //there are redendant RPCs. to make the difference, we add
                //the routing key to the RPC
                String currentRPCandRK = currentRoutingKey + " * " + currentRPC;

                addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME,
                        envelope.getRoutingKey(), messageCore, properties });

                //verify if it's a new or a deja-vu RPC in the main 
                //rpc method tracking list
                if (!rpcMethodsList.contains(currentRPCandRK)) {
                    rpcMethodsList.add(currentRPCandRK);
                }

                //verify if it's a new or a deja-vu routing key in the main 
                //routing keys tracking list
                if (!routingKeysList.contains(currentRoutingKey)) {
                    routingKeysList.add(currentRoutingKey);
                }

                //verify if it's a new or a deja-vu routing key in the stats 
                //recording list and init stats
                //logically it can be added to the condition above but
                //I prefer it this way
                if (!myRKStatsCounterMap.containsKey(currentRoutingKey)) {
                    myRKStatsCounterMap.put(currentRoutingKey, 1);
                    myRKStatsPercentageMap.put(currentRoutingKey, (1.0f / messageCounter) * 100);
                    myRKStatsFiveSecondsCounterMap.put(currentRoutingKey, 1);
                    myRKStatsTotalDataSizeMap.put(currentRoutingKey, (body.length / 1024F));
                    myRKStatsMeanDataSizeMap.put(currentRoutingKey, (body.length / 1024F));
                    dynamicRKRates.add(1);
                } else {
                    //FIXED: chaos.. update: everything is fine
                    myRKStatsCounterMap.put(currentRoutingKey, myRKStatsCounterMap.get(currentRoutingKey) + 1);
                    for (String rk : routingKeysList) {
                        //loop all routing keys because it depends on the 
                        //total number of recieved messages.
                        myRKStatsPercentageMap.put(rk,
                                (((float) myRKStatsCounterMap.get(rk)) / messageCounter) * 100);
                    }
                    myRKStatsTotalDataSizeMap.put(currentRoutingKey,
                            myRKStatsTotalDataSizeMap.get(currentRoutingKey) + (body.length / 1024.0F));
                    myRKStatsMeanDataSizeMap.put(currentRoutingKey,
                            ((float) myRKStatsTotalDataSizeMap.get(currentRoutingKey))
                                    / myRKStatsCounterMap.get(currentRoutingKey));
                }

                //verify if it's a new or a deja-vu rpc in the stats 
                //recording list and init stats
                if (!myRPCStatsCounterMap.containsKey(currentRPCandRK)) {
                    myRPCStatsCounterMap.put(currentRPCandRK, 1);
                    myRPCStatsPercentageMap.put(currentRPCandRK, (1.0f / messageCounter) * 100);
                    myRPCRKExchangeMap.put(currentRPCandRK,
                            new String[] { EXCHANGE_NAME, currentRoutingKey, currentRPC });
                } else {
                    myRPCStatsCounterMap.put(currentRPCandRK, myRPCStatsCounterMap.get(currentRPCandRK) + 1);
                    for (String rpc : rpcMethodsList) {
                        //loop all rpc because it depends on the 
                        //total number of received messages.
                        //using the messageCounter is OK because even 
                        //messages that are not RPCs are considered as
                        //RPCs with a 'N/A' RPC type.
                        myRPCStatsPercentageMap.put(rpc,
                                (((float) myRPCStatsCounterMap.get(rpc)) / messageCounter) * 100);
                    }
                }

                // Properties object added to message object
                displayNewMessage(new Object[] { messageCounter, getFormattedTime(), EXCHANGE_NAME,
                        envelope.getRoutingKey(), currentRPC, properties });

                //FIXED: custom messages (ex. used for test) may be less  
                //longer than 30 character which raises an exception.
                String messagePreview = messageCore;
                if (messageCore.length() > 100) {
                    messagePreview = messageCore.substring(0, 85) + "...";
                }

                System.out.println("MSG [" + messageCounter + "]:" + " | rk: " + envelope.getRoutingKey()
                        + " | en: " + envelope.getExchange() + " | ts: " + properties.getTimestamp() + " | ct: "
                        + properties.getContentType() + " | ce: " + properties.getContentEncoding() + " | mp: "
                        + messagePreview + " |");
                messageCounter++;
            }

            private String getFormattedTime() {
                return myDateFormatter.format(new Date());
            }

            private String getRPCMethod(String messageCore) {
                String rpcMethodName = "N/A";
                //clean up the message core
                messageCore = messageCore.replaceAll("[\\p{Punct}&&[^,:_]]", "");
                //transform the message core to a list of tokens
                StringTokenizer st1 = new StringTokenizer(messageCore, ",");
                //locate the string token 'method' and save the next
                //one which is the rpc method name
                while (st1.hasMoreElements()) {
                    String token = (String) st1.nextElement();
                    if (token.trim().startsWith("method")) {
                        rpcMethodName = token.substring(9);
                    }
                }
                return rpcMethodName;
            }
        };
        myChannel.basicConsume(QUEUE_NAME, true, myConsumer);
    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    } catch (TimeoutException ex) {
        ex.printStackTrace(System.out);
    }
}

From source file:tracer.ui.LoggerUI.java

License:Apache License

private void connectRMQNode(Object[] rmqNodeData) {
    try {//ww  w . jav  a 2 s  .co m
        com.rabbitmq.client.ConnectionFactory myFactory = new ConnectionFactory();
        myFactory.setHost((String) rmqNodeData[0]);
        myFactory.setPort((Integer) rmqNodeData[1]);
        myFactory.setUsername((String) rmqNodeData[2]);
        myFactory.setPassword((String) rmqNodeData[3]);
        myFactory.setVirtualHost((String) rmqNodeData[4]);
        myFactory.setConnectionTimeout((Integer) rmqNodeData[5]);

        //Automatic recovery from network failures
        myFactory.setAutomaticRecoveryEnabled(true);
        System.out.println("automatic recovery from network failures is " + "enabled");

        System.out.println("creating new connection..");
        myConnection = myFactory.newConnection();
        System.out.println("creating new channel..");
        myChannel = myConnection.createChannel();
        System.out.println("declaring the log exchange..");
        myChannel.exchangeDeclare(LOG_EXCHANGE_NAME, LOG_EXCHANGE_TYPE, true, false, true, null);

        System.out.println("creating random queue..");
        String QUEUE_NAME = myChannel.queueDeclare().getQueue();

        System.out.println("binding to exchange=" + LOG_EXCHANGE_NAME + " using binding key=" + LOG_BK);
        myChannel.queueBind(QUEUE_NAME, LOG_EXCHANGE_NAME, LOG_BK);

        System.out.println("waiting for messages, this may take few seconds" + "..");

        com.rabbitmq.client.Consumer myConsumer = new DefaultConsumer(myChannel) {
            int messageCounter = 1;

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                String messageCore = new String(body, "UTF-8");

                addNewMessageToInbox(new Object[] { messageCounter, getFormattedTime(),
                        envelope.getRoutingKey(), messageCore });

                // Properties object added to message object
                displayNewMessage(new Object[] { messageCounter, getFormattedTime(), envelope.getRoutingKey(),
                        messageCore });
                messageCounter++;
            }

            private String getFormattedTime() {
                return myDateFormatter.format(new Date());
            }

            public void addNewMessageToInbox(Object[] message) {
                //inbox.add(message);
            }

            private void displayNewMessage(Object[] data) {
                DefaultTableModel logTableModel = (DefaultTableModel) logTable.getModel();
                logTableModel.addRow(data);
                //                    for (int i = 0; i < data.length; i++) {
                //                        logTable.setValueAt(data[i], logTable.getRowCount()+1,
                //                                i);
                //                    }
            }
        };
        myChannel.basicConsume(QUEUE_NAME, true, myConsumer);
    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    } catch (TimeoutException ex) {
        ex.printStackTrace(System.out);
    }
}

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

License:Apache License

@Produces
@ApplicationScoped//ww  w. j  a  v a  2s.  c o  m
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;
}

From source file:zebrogamq.gamelogic.ChannelsManager.java

License:Open Source License

private ConnectionFactory getConnectionFactory(final GameLogicState state) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(Util.getRabbitMQProperties().getProperty("gameLogicBrokerHost"));
    factory.setUsername(state.login);//  w ww .ja va  2 s .  com
    factory.setPassword(state.password);
    factory.setVirtualHost(state.virtualHost);
    factory.setPort(Integer.valueOf(Util.getRabbitMQProperties().getProperty("gameLogicBrokerPort",
            String.valueOf(factory.getPort()))));
    factory.setConnectionTimeout(CONNECTION_ESTABLISHMENT_TIMEOUT);
    // set the heartbeat value for the amqp connections
    // to avoid the keeping of obsolete consumers
    factory.setRequestedHeartbeat(Integer.valueOf(Util.getRabbitMQProperties()
            .getProperty("amqpConnectionHeartbeat", String.valueOf(factory.getRequestedHeartbeat()))));
    return factory;
}

From source file:zipkin2.autoconfigure.collector.rabbitmq.ZipkinRabbitMQCollectorProperties.java

License:Apache License

public RabbitMQCollector.Builder toBuilder()
        throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException {
    final RabbitMQCollector.Builder result = RabbitMQCollector.builder();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    if (concurrency != null)
        result.concurrency(concurrency);
    if (connectionTimeout != null)
        connectionFactory.setConnectionTimeout(connectionTimeout);
    if (queue != null)
        result.queue(queue);//from   w w w. j a v  a 2s .  c  om

    if (uri != null) {
        connectionFactory.setUri(uri);
    } else {
        if (addresses != null)
            result.addresses(addresses);
        if (password != null)
            connectionFactory.setPassword(password);
        if (username != null)
            connectionFactory.setUsername(username);
        if (virtualHost != null)
            connectionFactory.setVirtualHost(virtualHost);
        if (useSsl != null && useSsl)
            connectionFactory.useSslProtocol();
    }
    result.connectionFactory(connectionFactory);
    return result;
}