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:li.barter.chat.AbstractRabbitMQConnector.java

License:Open Source License

/**
 * Connect to the broker and create the exchange
 * /*from   www  . j  a v  a  2 s  . c o  m*/
 * @return success
 */
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);
        connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT_INTERVAL);
        mConnection = connectionFactory.newConnection();
        mChannel = mConnection.createChannel();
        mChannel.exchangeDeclare(mExchange, mExchangeType.key);

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

From source file:mx.bigdata.utils.amqp.HaConsumer.java

License:Apache License

public HaConsumer(String tag, String key, AMQPClientHelper amqp, ConnectionFactory factory) {
    super(tag, key, amqp, factory);
    if (factory.getRequestedHeartbeat() == 0) {
        factory.setRequestedHeartbeat(DEFAULT_HEARTBEAT_SECONDS);
    }//  www  . ja v a  2  s .c om
}

From source file:mx.bigdata.utils.amqp.HaPublisher.java

License:Apache License

public HaPublisher(String tag, String key, AMQPClientHelper amqp, ConnectionFactory factory) throws Exception {
    super(tag, key, amqp, factory);
    if (factory.getRequestedHeartbeat() == 0) {
        factory.setRequestedHeartbeat(DEFAULT_HEARTBEAT_SECONDS);
    }/*from   ww  w  .  j  a  v a  2  s  . c  om*/
    initConfirms();
}

From source file:net.lshift.camdisplay.Main.java

License:Open Source License

public Main(String host, String exch, String nickname, final String mixerSpec) throws IOException {
    frame = new JFrame("RabbitCam: " + host + "/" + exch);
    panel = new JPanel();
    componentMap = new HashMap();

    setupWindowDressing(exch, nickname, frame, panel);
    frame.pack();/*from  www .  j  a  va  2  s . co  m*/
    frame.show();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    textInput.requestFocusInWindow();

    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(host);
    cf.setRequestedHeartbeat(0);
    conn = cf.newConnection();

    ch = conn.createChannel();

    ch.exchangeDeclare(exch, "fanout");

    String queueName = ch.queueDeclare().getQueue();
    ch.queueBind(queueName, exch, "");
    ch.basicConsume(queueName, true, new DefaultConsumer(ch) {
        public void handleShutdownSignal(String consumerTag, ShutdownSignalException s) {
            if (s.getReason() instanceof java.io.EOFException) {
                JOptionPane.showMessageDialog(frame, "AMQP server disconnected.", "Connection closed",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                SwingUtil.complain("Connection closed", null, s);
            }
            System.exit(1);
        }

        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String routingKey = envelope.getRoutingKey();
            String contentType = properties.getContentType();

            if (contentType.equals("text/plain")) {
                handleText(routingKey, new String(body));
                return;
            }

            CamstreamComponent comp;
            if (!componentMap.containsKey(routingKey)) {
                comp = new CamstreamComponent(mixerSpec);
                addComponent(routingKey, comp);
                frame.pack();
            } else {
                comp = (CamstreamComponent) componentMap.get(routingKey);
            }
            if (comp.handleDelivery(contentType, body)) {
                frame.pack();
            }
        }
    });
}

From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java

License:Apache License

/**
 *
 * @return Connection Factory for RMQ/*from  ww w  . j  a  v a2s  .  c om*/
 * @throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException if Malformed URI has been passed
 */
public ConnectionFactory getConnectionFactory()
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
    ConnectionFactory factory = new ConnectionFactory();
    if (this.uri != null && !this.uri.isEmpty()) {
        try {
            factory.setUri(this.uri);
        } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException e) {
            LOG.error("Failed to parse uri", e);
            throw e;
        }
    } else {
        factory.setHost(this.host);
        factory.setPort(this.port);
        factory.setVirtualHost(this.virtualHost);
        factory.setUsername(this.username);
        factory.setPassword(this.password);
    }

    if (this.automaticRecovery != null) {
        factory.setAutomaticRecoveryEnabled(this.automaticRecovery);
    }
    if (this.connectionTimeout != null) {
        factory.setConnectionTimeout(this.connectionTimeout);
    }
    if (this.networkRecoveryInterval != null) {
        factory.setNetworkRecoveryInterval(this.networkRecoveryInterval);
    }
    if (this.requestedHeartbeat != null) {
        factory.setRequestedHeartbeat(this.requestedHeartbeat);
    }
    if (this.topologyRecovery != null) {
        factory.setTopologyRecoveryEnabled(this.topologyRecovery);
    }
    if (this.requestedChannelMax != null) {
        factory.setRequestedChannelMax(this.requestedChannelMax);
    }
    if (this.requestedFrameMax != null) {
        factory.setRequestedFrameMax(this.requestedFrameMax);
    }

    return factory;
}

From source file:org.apache.flume.amqp.AmqpSource.java

License:Apache License

@VisibleForTesting
static ConnectionFactory createConnectionFactoryFrom(Context context) {
    String host = context.getString(AmqpSourceConfigurationConstants.HOST, Constants.Defaults.HOST);
    int port = context.getInteger(AmqpSourceConfigurationConstants.PORT, Constants.Defaults.PORT);
    String virtualHost = context.getString(AmqpSourceConfigurationConstants.VIRTUAL_HOST,
            Constants.Defaults.VIRTUAL_HOST);
    String userName = context.getString(AmqpSourceConfigurationConstants.USER_NAME,
            Constants.Defaults.USER_NAME);
    String password = context.getString(AmqpSourceConfigurationConstants.PASSWORD, Constants.Defaults.PASSWORD);
    int connectionTimeout = context.getInteger(AmqpSourceConfigurationConstants.CONNECTION_TIMEOUT,
            Constants.Defaults.CONNECTION_TIMEOUT);
    int requestHeartbeat = context.getInteger(AmqpSourceConfigurationConstants.REQUEST_HEARTBEAT,
            Constants.Defaults.REQUESTED_HEARTBEAT);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost(host);/* ww w.j a  v a  2s .c  o  m*/
    connectionFactory.setPort(port);
    connectionFactory.setVirtualHost(virtualHost);
    connectionFactory.setUsername(userName);
    connectionFactory.setPassword(password);
    connectionFactory.setConnectionTimeout(connectionTimeout);
    connectionFactory.setRequestedHeartbeat(requestHeartbeat);

    return connectionFactory;
}

From source file:org.ballerinalang.messaging.rabbitmq.util.ConnectionUtils.java

License:Open Source License

/**
 * Creates a RabbitMQ Connection using the given connection parameters.
 *
 * @param connectionConfig Parameters used to initialize the connection.
 * @return RabbitMQ Connection object.//  w  w  w  . j  a va  2 s. c  o  m
 */
public static Connection createConnection(BMap<String, BValue> connectionConfig) {
    try {
        ConnectionFactory connectionFactory = new ConnectionFactory();

        String host = RabbitMQUtils.getStringFromBValue(connectionConfig,
                RabbitMQConstants.RABBITMQ_CONNECTION_HOST);
        connectionFactory.setHost(host);

        int port = RabbitMQUtils.getIntFromBValue(connectionConfig, RabbitMQConstants.RABBITMQ_CONNECTION_PORT,
                LOGGER);
        connectionFactory.setPort(port);

        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_USER) != null) {
            connectionFactory.setUsername(RabbitMQUtils.getStringFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_USER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_PASS) != null) {
            connectionFactory.setPassword(RabbitMQUtils.getStringFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_PASS));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_TIMEOUT) != null) {
            connectionFactory.setConnectionTimeout(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_TIMEOUT, LOGGER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_HANDSHAKE_TIMEOUT) != null) {
            connectionFactory.setHandshakeTimeout(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_HANDSHAKE_TIMEOUT, LOGGER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_SHUTDOWN_TIMEOUT) != null) {
            connectionFactory.setShutdownTimeout(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_SHUTDOWN_TIMEOUT, LOGGER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_HEARTBEAT) != null) {
            connectionFactory.setRequestedHeartbeat(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_HEARTBEAT, LOGGER));
        }
        return connectionFactory.newConnection();
    } catch (IOException | TimeoutException exception) {
        LOGGER.error(RabbitMQConstants.CREATE_CONNECTION_ERROR, exception);
        throw new RabbitMQConnectorException(RabbitMQConstants.CREATE_CONNECTION_ERROR + exception.getMessage(),
                exception);
    }
}

From source file:org.eclipse.hono.dispatcher.amqp.AmqpConnection.java

License:Open Source License

private static Connection createConnection(final String amqpUri) throws NoSuchAlgorithmException,
        KeyManagementException, URISyntaxException, IOException, TimeoutException {
    final ConnectionFactory factory = new ConnectionFactory();

    AmqpConnection.LOGGER.info("Connecting to " + amqpUri);

    factory.setUri(amqpUri);/*from   ww  w. ja v  a 2s  . com*/
    factory.setRequestedHeartbeat(60);
    factory.setAutomaticRecoveryEnabled(true);
    factory.setTopologyRecoveryEnabled(true);
    factory.setExceptionHandler(new ExceptionHandler() {
        @Override
        public void handleUnexpectedConnectionDriverException(final Connection conn,
                final Throwable exception) {
            AmqpConnection.LOGGER.warn("UnexpectedConnectionDriverException", exception);
        }

        @Override
        public void handleReturnListenerException(final Channel channel, final Throwable exception) {
            AmqpConnection.LOGGER.warn("ReturnListenerException", exception);
        }

        @Override
        public void handleFlowListenerException(final Channel channel, final Throwable exception) {
            AmqpConnection.LOGGER.warn("FlowListenerException", exception);
        }

        @Override
        public void handleConfirmListenerException(final Channel channel, final Throwable exception) {
            AmqpConnection.LOGGER.warn("ConfirmListenerException", exception);
        }

        @Override
        public void handleBlockedListenerException(final Connection connection, final Throwable exception) {
            AmqpConnection.LOGGER.warn("BlockedListenerException", exception);
        }

        @Override
        public void handleConsumerException(final Channel channel, final Throwable exception,
                final Consumer consumer, final String consumerTag, final String methodName) {
            AmqpConnection.LOGGER.warn("ConsumerException", exception);
        }

        @Override
        public void handleConnectionRecoveryException(final Connection conn, final Throwable exception) {
            AmqpConnection.LOGGER.warn("ConnectionRecoveryException", exception);
        }

        @Override
        public void handleChannelRecoveryException(final Channel ch, final Throwable exception) {
            AmqpConnection.LOGGER.warn("ChannelRecoveryException", exception);
        }

        @Override
        public void handleTopologyRecoveryException(final Connection conn, final Channel ch,
                final TopologyRecoveryException exception) {
            AmqpConnection.LOGGER.warn("TopologyRecoveryException", exception);
        }
    });

    return factory.newConnection();
}

From source file:org.kairosdb.plugin.rabbitmq.core.RabbitmqService.java

License:MIT License

@Override
public void start() throws KairosDBException {

    try {/*ww  w. j a va2 s.  c o m*/
        LOGGER.info("[KRMQ] Starting to RabbitMQ consumer thread.");

        // Socket abstract connection with broker
        ConnectionFactory rabbitmqConnectionFactory = new ConnectionFactory();
        rabbitmqConnectionFactory.setHost(rabbmitmqHost);
        rabbitmqConnectionFactory.setVirtualHost(rabbitmqVirtualHost);
        rabbitmqConnectionFactory.setUsername(rabbitmqUser);
        rabbitmqConnectionFactory.setPassword(rabbitmqPassword);
        rabbitmqConnectionFactory.setPort(rabbitmqPort);
        rabbitmqConnectionFactory.setConnectionTimeout(rabbitmqTimeout);
        rabbitmqConnectionFactory.setRequestedChannelMax(rabbitmqChannelMax);
        rabbitmqConnectionFactory.setRequestedFrameMax(rabbitmqFrameMax);
        rabbitmqConnectionFactory.setRequestedHeartbeat(rabbitmqHearbeat);
        rabbitmqConnectionFactory.setAutomaticRecoveryEnabled(true);

        // Get KairosDatastore implementation
        KairosDatastore kairosDatabase = googleInjector.getInstance(KairosDatastore.class);

        // Create consumer thread
        RabbitmqConsumer consumer = new RabbitmqConsumer(kairosDatabase, rabbitmqConnectionFactory,
                bindingsFile, configurationJSONFieldValue, configurationJSONTimeStamp, configurationJSONTags,
                configurationCSVSeperator, configurationDefaultContentType);

        // Start consumer thread
        consumerThread = new Thread(consumer);
        consumerThread.start();

    } catch (Exception e) {
        LOGGER.error("[KRMQ] An error occurred: ", e);
    }
}

From source file:org.springframework.amqp.rabbit.MulticastMain.java

License:Mozilla Public License

public static void main(String[] args) {
    Options options = getOptions();//from  w  w w . ja  v a2  s  .com
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String hostName = strArg(cmd, 'h', "localhost");
        int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int messageCount = intArg(cmd, 'N', 0);
        int consumerCount = intArg(cmd, 'y', 1);
        int connectionCount = cmd.hasOption('c') ? 1 : consumerCount;
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        boolean autoAck = cmd.hasOption('a');
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<String> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);

        // setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        factory.setPort(portNumber);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        Connection[] consumerConnections = new Connection[connectionCount];
        for (int i = 0; i < connectionCount; i++) {
            Connection conn = factory.newConnection();
            consumerConnections[i] = conn;
        }
        Thread[] consumerThreads = new Thread[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            Connection conn = consumerConnections[i % connectionCount];
            Channel channel = conn.createChannel();
            if (consumerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null)
                    .getQueue();
            QueueingConsumer consumer = new QueueingConsumer(channel);
            if (prefetchCount > 0)
                channel.basicQos(prefetchCount);
            channel.basicConsume(queueName, autoAck, consumer);
            channel.queueBind(queueName, exchangeName, id);
            Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit));
            consumerThreads[i] = t;
            t.start();
        }
        Thread[] producerThreads = new Thread[producerCount];
        Connection[] producerConnections = new Connection[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            Connection conn = factory.newConnection();
            producerConnections[i] = conn;
            Channel channel = conn.createChannel();
            if (producerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize,
                    1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount);
            channel.addReturnListener(p);
            Thread t = new Thread(p);
            producerThreads[i] = t;
            t.start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
        }
        for (int i = 0; i < connectionCount; i++) {
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}