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(ExecutorService executor) throws IOException, TimeoutException 

Source Link

Document

Create a new broker connection.

Usage

From source file:com.flipkart.bifrost.framework.Connection.java

License:Apache License

/**
 * Start the connection. This will try to connect to the cluster hosts provided in the contructor.
 * Will throw an error in case of failure.
 * @throws BifrostException in case of connection failure.
 *//*from w w w  .j  a v a 2 s. co  m*/
public void start() throws BifrostException {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    Address brokers[] = new Address[hosts.size()];
    int i = 0;
    for (String member : hosts) {
        brokers[i++] = new Address(member);
    }
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(true);
    try {
        connection = connectionFactory.newConnection(brokers);
    } catch (IOException e) {
        throw new BifrostException(BifrostException.ErrorCode.IO_ERROR, "Could not connect", e);
    }
}

From source file:com.sitewhere.rabbitmq.RabbitMqInboundEventReceiver.java

License:Open Source License

@Override
public void start() throws SiteWhereException {
    executors = Executors.newFixedThreadPool(getNumConsumers());
    try {//  w ww  . j av a2 s  .c om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(getConnectionUri());
        this.connection = factory.newConnection(executors);
        this.channel = connection.createChannel();

        LOGGER.info("RabbitMQ receiver connected to: " + getConnectionUri());

        channel.queueDeclare(getQueueName(), isDurable(), false, false, null);

        LOGGER.info("RabbitMQ receiver using " + (isDurable() ? "durable " : "") + "queue: " + getQueueName());

        // Add consumer callback for channel.
        Consumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                EventProcessingLogic.processRawPayload(RabbitMqInboundEventReceiver.this, body, null);
            }
        };
        channel.basicConsume(getQueueName(), true, consumer);
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event receiver.", e);
    }
}

From source file:com.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

/**
 * Build an instance./*from  w  w w.java  2 s .  c  o  m*/
 *
 * @param lifecycle     The current application lifecyle
 * @param configuration The current application configuration
 * @since 16.05.19
 */
@Inject
public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) {
    this.configuration = configuration;
    try {
        final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI);
        if (uri == null || uri.isEmpty()) {
            throw new RuntimeException("URI is empty");
        }
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(uri);
        connectionFactory
                .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT));
        connectionFactory
                .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY));
        connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT));
        connectionFactory.setAutomaticRecoveryEnabled(
                configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY));
        if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) {
            connectionFactory.useSslProtocol();
        }

        final ExecutorService es = Executors
                .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR));
        this.rabbitConnection = connectionFactory.newConnection(es);
        RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}",
                String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "",
                        connectionFactory.getHost(), connectionFactory.getPort(),
                        connectionFactory.getVirtualHost()));
    } catch (Exception ex) {
        this.rabbitConnection = null;
        if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) {
            RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex);
            throw new RuntimeException(ex);
        } else {
            RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage());
        }
    }

    lifecycle.addStopHook(() -> {
        RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ");
        if (this.rabbitConnection != null) {
            this.rabbitConnection.close();
        }
        return CompletableFuture.completedFuture(null);
    });
}

From source file:dk.au.cs.karibu.backend.rabbitmq.RabbitMQPollingConsumer.java

License:Apache License

@Override
public void openChannelAndSetRouting() throws IOException {
    theLogger.info(// w w  w  . j a  va  2  s .  c  o  m
            "openChannelAndSetRouting: Exchange:" + exchangeConfiguration + " Queue: " + queueConfiguration);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(exchangeConfiguration.getUsername());
    factory.setPassword(exchangeConfiguration.getPassword());
    if (exchangeConfiguration.isSSLConnection()) {
        try {
            factory.useSslProtocol();
        } catch (KeyManagementException e) {
            String trace = ExceptionUtils.getStackTrace(e);
            theLogger.error("KeyMgtException: " + trace);
        } catch (NoSuchAlgorithmException e) {
            String trace = ExceptionUtils.getStackTrace(e);
            theLogger.error("NoSuchAlgoritmException: " + trace);
        }
    }
    connection = factory.newConnection(exchangeConfiguration.getServerAddressList());

    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeConfiguration.getExchangeName(), exchangeConfiguration.getExchangeType(),
            exchangeConfiguration.isExchangeDurable());

    // 'RabbitMQ in Action' p 102 
    Map<String, Object> moreArguments = new HashMap<String, Object>();
    moreArguments.put("ha-mode", "all");
    moreArguments.put("x-ha-policy", "all");
    // TODO: find out why this does not work! 
    channel.queueDeclare(queueConfiguration.getQueueName(), queueConfiguration.isQueueDurable(),
            queueConfiguration.isQueueExclusive(), queueConfiguration.isQueueAutoDelete(), moreArguments);
    channel.queueBind(queueConfiguration.getQueueName(), exchangeConfiguration.getExchangeName(),
            queueConfiguration.getRoutingKey());

    consumer = new QueueingConsumer(channel);
    // Tell RabbitMQ to await acknowledgement before removing
    // msg from the queue. See http://www.rabbitmq.com/tutorials/tutorial-two-java.html
    boolean autoAck = false;
    channel.basicConsume(queueConfiguration.getQueueName(), autoAck, consumer);
    // Set the prefetch count to limit the amount of msg sent
    // to the daemons before they are acknowledged. Fixes a
    // bug that would induce an out-of-memory error in the
    // daemons during high transfer rates.
    // See http://www.rabbitmq.com/tutorials/tutorial-two-java.html 
    // in the 'fair dispatch' section
    int prefetchCount = 100; // ISSUE: what is the 'right' value here?
    channel.basicQos(prefetchCount);
}

From source file:dk.au.cs.karibu.producer.rabbitmq.RabbitChannelConnector.java

License:Apache License

@Override
public void openConnection() throws IOException {
    theLogger.info("openConnection: " + exchangeConfiguration);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(exchangeConfiguration.getUsername());
    factory.setPassword(exchangeConfiguration.getPassword());
    if (exchangeConfiguration.isSSLConnection()) {
        try {//from w  w  w. ja  v  a 2s .  c  o m
            factory.useSslProtocol();
        } catch (KeyManagementException e) {
            theLogger.error("KeyManagementException: " + e.getLocalizedMessage());
        } catch (NoSuchAlgorithmException e) {
            theLogger.error("NoSuchAlgorithmException: " + e.getLocalizedMessage());
        }
    }
    connection = factory.newConnection(exchangeConfiguration.getServerAddressList());

    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeConfiguration.getExchangeName(), exchangeConfiguration.getExchangeType(),
            exchangeConfiguration.isExchangeDurable());

    // The queue and the binding between queue and exchange is defined by the server side! 
}

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.client.RpcClientExample.java

License:Open Source License

private static Channel setupRabbitMQ() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);
    return channel;
}

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.service.Main.java

License:Open Source License

private static Channel setupRabbitMQ() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Arrays.asList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);
    return channel;
}

From source file:it.jugtorino.one.msvc.way.rabbit.reference.webapp.GeoIPResource.java

License:Open Source License

public GeoIPResource() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);

    client = new RpcClient(channel, "geoip_service_v1");
    client.startConsuming();/*from  w w  w  .j  a  va 2  s.co m*/
}

From source file:org.apache.pulsar.connect.rabbitmq.RabbitMQSource.java

License:Apache License

@Override
public void open(Map<String, String> config) throws Exception {
    rabbitMQConfig = RabbitMQConfig.load(config);
    if (rabbitMQConfig.getAmqUri() == null || rabbitMQConfig.getQueueName() == null) {
        throw new IllegalArgumentException("Required property not set.");
    }/*  ww w.  ja  v a 2  s. c om*/
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri(rabbitMQConfig.getAmqUri());
    rabbitMQConnection = connectionFactory.newConnection(rabbitMQConfig.getConnectionName());
    logger.info("A new connection to {}:{} has been opened successfully.",
            rabbitMQConnection.getAddress().getCanonicalHostName(), rabbitMQConnection.getPort());
    rabbitMQChannel = rabbitMQConnection.createChannel();
    rabbitMQChannel.queueDeclare(rabbitMQConfig.getQueueName(), false, false, false, null);
    com.rabbitmq.client.Consumer consumer = new RabbitMQConsumer(this.consumer, rabbitMQChannel);
    rabbitMQChannel.basicConsume(rabbitMQConfig.getQueueName(), consumer);
    logger.info("A consumer for queue {} has been successfully started.", rabbitMQConfig.getQueueName());
}

From source file:org.apache.pulsar.io.rabbitmq.RabbitMQSource.java

License:Apache License

@Override
public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception {
    rabbitMQConfig = RabbitMQConfig.load(config);
    if (rabbitMQConfig.getAmqUri() == null || rabbitMQConfig.getQueueName() == null) {
        throw new IllegalArgumentException("Required property not set.");
    }/*from   w  w w  .  java2 s. c  om*/
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri(rabbitMQConfig.getAmqUri());
    rabbitMQConnection = connectionFactory.newConnection(rabbitMQConfig.getConnectionName());
    logger.info("A new connection to {}:{} has been opened successfully.",
            rabbitMQConnection.getAddress().getCanonicalHostName(), rabbitMQConnection.getPort());
    rabbitMQChannel = rabbitMQConnection.createChannel();
    rabbitMQChannel.queueDeclare(rabbitMQConfig.getQueueName(), false, false, false, null);
    com.rabbitmq.client.Consumer consumer = new RabbitMQConsumer(this, rabbitMQChannel);
    rabbitMQChannel.basicConsume(rabbitMQConfig.getQueueName(), consumer);
    logger.info("A consumer for queue {} has been successfully started.", rabbitMQConfig.getQueueName());
}