Example usage for com.rabbitmq.client ConnectionFactory setAutomaticRecoveryEnabled

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

Introduction

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

Prototype

public void setAutomaticRecoveryEnabled(boolean automaticRecovery) 

Source Link

Document

Enables or disables <a href="https://www.rabbitmq.com/api-guide.html#recovery">automatic connection recovery</a>.

Usage

From source file:org.pascani.dsl.lib.infrastructure.rabbitmq.EndPoint.java

License:Open Source License

/**
 * Creates a RabbitMQ end point; that is, a connection to the RabbitMQ
 * server. This is commonly used by all RabbitMQ consumers and producers.
 * /*  w w  w  . j  a  va 2s . c o  m*/
 * @param uri
 *            The RabbitMQ connection URI
 * 
 * @throws Exception
 *             If something bat happens. Check exceptions in
 *             {@link ConnectionFactory#setUri(String)},
 *             {@link ConnectionFactory#newConnection()}, and
 *             {@link Connection#createChannel()}
 */
public EndPoint(final String uri) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setUri(uri);
    this.connection = factory.newConnection();
    this.channel = this.connection.createChannel();
}

From source file:org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode.java

License:Apache License

@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
    this.config = TbNodeUtils.convert(configuration, TbRabbitMqNodeConfiguration.class);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.config.getHost());
    factory.setPort(this.config.getPort());
    factory.setVirtualHost(this.config.getVirtualHost());
    factory.setUsername(this.config.getUsername());
    factory.setPassword(this.config.getPassword());
    factory.setAutomaticRecoveryEnabled(this.config.isAutomaticRecoveryEnabled());
    factory.setConnectionTimeout(this.config.getConnectionTimeout());
    factory.setHandshakeTimeout(this.config.getHandshakeTimeout());
    this.config.getClientProperties().forEach((k, v) -> factory.getClientProperties().put(k, v));
    try {/*  ww  w.j av a2s  . co  m*/
        this.connection = factory.newConnection();
        this.channel = this.connection.createChannel();
    } catch (Exception e) {
        throw new TbNodeException(e);
    }
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQOutputEventAdapterPublisher.java

License:Open Source License

/**
 * <pre>/*www .  java  2  s  . c o  m*/
 * Create a rabbitmq ConnectionFactory instance
 * </pre>
 * @param hostName
 * @param port
 * @param userName
 * @param password
 * @param virtualHost
 * @return
 */
private synchronized static ConnectionFactory getConnectionFactory(String hostName, int port, String userName,
        String password, String virtualHost) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);
    factory.setPort(port);
    factory.setUsername(userName);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);

    /**
     * Add connection recovery logic
     * @author Sang-Cheon Park
     * @date 2015.07.16
     */
    /**
     * connection that will recover automatically
     */
    factory.setAutomaticRecoveryEnabled(true);
    /**
     * attempt recovery every 5 seconds
     */
    factory.setNetworkRecoveryInterval(5 * 1000);
    /**
     * wait maximum 10 seconds to connect(if connection failed, will be retry to connect after 5 seconds)
     */
    factory.setConnectionTimeout(10 * 1000);

    return factory;
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.internal.EventAdapterHelper.java

License:Apache License

/**
 * <pre>//from  w  ww . j a  va2  s  . c  o  m
 * Create a rabbitmq ConnectionFactory instance
 * </pre>
 * @param hostName
 * @param port
 * @param userName
 * @param password
 * @param virtualHost
 * @return
 */
public synchronized static ConnectionFactory getConnectionFactory(String hostName, int port, String userName,
        String password, String virtualHost) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);
    factory.setPort(port);
    factory.setUsername(userName);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);

    /**
     * Add connection recovery logic
     * @author Sang-Cheon Park
     * @date 2015.07.16
     */
    /**
     * connection that will recover automatically
     */
    factory.setAutomaticRecoveryEnabled(true);
    /**
     * attempt recovery every 5 seconds
     */
    factory.setNetworkRecoveryInterval(5 * 1000);
    /**
     * wait maximum 10 seconds to connect(if connection failed, will be retry to connect after 5 seconds)
     */
    factory.setConnectionTimeout(10 * 1000);

    return factory;
}

From source file:ox.softeng.burst.service.message.RabbitMessageService.java

public RabbitMessageService(EntityManagerFactory emf, Properties properties)
        throws IOException, TimeoutException {

    exchange = properties.getProperty("rabbitmq.exchange");
    queue = properties.getProperty("rabbitmq.queue");
    entityManagerFactory = emf;//from   w  w w  .  j av  a2 s  .  com
    consumerCount = Utils.convertToInteger("message.service.thread.size",
            properties.getProperty("message.service.consumer.size"), 1);

    String host = properties.getProperty("rabbitmq.host");
    String username = properties.getProperty("rabbitmq.user", ConnectionFactory.DEFAULT_USER);
    String password = properties.getProperty("rabbitmq.password", ConnectionFactory.DEFAULT_PASS);
    Integer port = Utils.convertToInteger("rabbitmq.port", properties.getProperty("rabbitmq.port"),
            ConnectionFactory.DEFAULT_AMQP_PORT);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setPort(port);
    factory.setHost(host);
    factory.setAutomaticRecoveryEnabled(true);
    factory.setThreadFactory(new NamedThreadFactory("consumer"));

    connection = factory.newConnection();

    logger.info("Creating new RabbitMQ Service using: \n" + "  host: {}:{}\n" + "  user: {}\n"
            + "  exchange: {}\n" + "  queue: {}", host, port, username, exchange, queue);
}

From source file:ox.softeng.burst.services.RabbitService.java

License:Open Source License

public RabbitService(String rabbitMQHost, Integer port, String username, String password,
        String rabbitMQExchange, String rabbitMQQueue, EntityManagerFactory emf)
        throws IOException, TimeoutException, JAXBException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(username);//from   ww  w .j  a  v a 2 s .c o  m
    factory.setPassword(password);
    factory.setPort(port);
    factory.setHost(rabbitMQHost);
    factory.setAutomaticRecoveryEnabled(true);

    entityManagerFactory = emf;
    this.rabbitMQQueue = rabbitMQQueue;
    this.rabbitMQExchange = rabbitMQExchange;

    connection = factory.newConnection();
    unmarshaller = JAXBContext.newInstance(MessageDTO.class).createUnmarshaller();
}

From source file:rapture.exchange.rabbitmq.RabbitExchangeHandler.java

License:Open Source License

@Override
public synchronized void setConfig(Map<String, String> config) {
    // Attempt to bind to RabbitMQ
    ConnectionFactory factory = new ConnectionFactory();
    logger.info(Messages.getString("RabbitExchangeHandler.config")); //$NON-NLS-1$
    try {/*from  ww w.j  ava 2 s.  c o  m*/
        String uri = MultiValueConfigLoader.getConfig("RABBITMQ-" //$NON-NLS-1$
                + instanceName);
        if (uri == null || uri.isEmpty()) {
            uri = "amqp://guest:guest@localhost:5672/%2f"; //$NON-NLS-1$
        }
        factory.setUri(uri);
        factory.setAutomaticRecoveryEnabled(true);
        logger.debug(Messages.getString("RabbitExchangeHandler.creatingChannel")); //$NON-NLS-1$
        connection = factory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                // This should theoretically be called when we disconnect
                // from RabbitMQ, but due to a bug in the client library it
                // instead gets invoked
                // when reconnecting. This may change in future versions of
                // amqp-client so may need to revisit
                logger.info("Reconnected to RabbitMQ");

            }
        });
        logger.debug(Messages.getString("RabbitExchangeHandler.connectionMade")); //$NON-NLS-1$
        channel = connection.createChannel();
        channel.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                logger.info("Disconnected from RabbitMQ. Cause :" + cause.getMessage());
                logger.debug(ExceptionToString.format(cause));
            }
        });
        logger.debug(Messages.getString("RabbitExchangeHandler.channelCreated")); //$NON-NLS-1$
        channel.basicQos(100);
        channel.addReturnListener(new ReturnListener() {

            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                    AMQP.BasicProperties properties, byte[] body) throws IOException {
                logger.debug(
                        String.format(Messages.getString("RabbitExchangeHandler.returnListener"), replyCode, //$NON-NLS-1$
                                replyText));
            }

        });
        channel.addFlowListener(new FlowListener() {

            @Override
            public void handleFlow(boolean active) throws IOException {
                logger.debug(String.format(Messages.getString("RabbitExchangeHandler.Flow"), active)); //$NON-NLS-1$
            }

        });

        replyQueueName = channel.queueDeclare().getQueue();
        logger.info("RPC reply queue is " + replyQueueName);
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(replyQueueName, true, consumer);

    } catch (Exception e) {
        String message = Messages.getString("RabbitExchangeHandler.noConnect");
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, message, e);
    }
}

From source file:rmq.sender.impl.MQSender.java

License:Apache License

@Override
public void start() {
    SSLContext c = null;/* ww  w  . j  av  a  2 s.  c o m*/
    try {
        char[] pass = "changeit".toCharArray();
        KeyStore tks = KeyStore.getInstance("JKS");
        tks.load(new FileInputStream(
                "/root/test-project/topology-current/" + "/src/main/resources/client/client_cacerts.jks"),
                pass);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(tks);

        c = SSLContext.getInstance("TLSv1.2");
        c.init(null, tmf.getTrustManagers(), null);
    } catch (Exception e) {
        log.error(E_CREATE_CHAN, e);
    }
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setNetworkRecoveryInterval(RECOVERY_INTERVAL);
    factory.useSslProtocol(c);
    try {
        factory.setUri(url);
        if (executorService != null) {
            conn = factory.newConnection(executorService);
        } else {
            conn = factory.newConnection();
        }
        channel = conn.createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        /*
         * Setting the following parameters to queue
         * durable    - true
         * exclusive  - false
         * autoDelete - false
         * arguments  - null
         */
        channel.queueDeclare(this.queueName, true, false, true, null);
        channel.queueBind(queueName, exchangeName, routingKey);
    } catch (Exception e) {
        log.error(E_CREATE_CHAN, e);
    }
    log.info("Connection started");
}

From source file:tracer.manager.Manager.java

License:Apache License

public void connectToRabbitNode() {
    try {//ww  w .  j  av a 2  s  .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 {//from  w  w w . j  a  v a2  s .c o 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);
    }
}