Java Code Examples for com.rabbitmq.client.ConnectionFactory#setConnectionTimeout()

The following examples show how to use com.rabbitmq.client.ConnectionFactory#setConnectionTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Publisher.java    From rabbitmq-tutorial with MIT License 8 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:guest@localhost");
    factory.setConnectionTimeout(300000);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare("my-queue", true, false, false, null);

    int count = 0;

    while (count < 5000) {
        String message = "Message number " + count;

        channel.basicPublish("", "my-queue", null, message.getBytes());
        count++;
        System.out.println("Published message: " + message);

        Thread.sleep(5000);
    }
}
 
Example 2
Source File: QueueClient.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private ConnectionFactory createConnectionFactory() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(this.config.getUsername());
    factory.setPassword(this.config.getPassword());
    factory.setVirtualHost(this.config.getVirtualHost());

    factory.setAutomaticRecoveryEnabled(true);
    factory.setConnectionTimeout(this.config.getConnectionTimeout());
    factory.setNetworkRecoveryInterval(this.config.getNetworkRecoveryInterval());

    if (this.threadFactory != null) {
        factory.setThreadFactory(this.threadFactory);
    }

    return factory;
}
 
Example 3
Source File: ConnectionConfiguration.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Override
public Connection createConnection(ConnectionFactory connectionFactory)
    throws IOException, TimeoutException {
  connectionFactory.setUsername(username);
  connectionFactory.setPassword(password);
  connectionFactory.setRequestedHeartbeat(requestedConnectionHeartbeatTimeout);
  connectionFactory.setConnectionTimeout(connectTimeout);
  if (secure) {
    final SSLContext sslContext;
    try {
      sslContext = sslContextFactory.createSSLContext();
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException("error during connect, fatal system configuration", e);
    }
    connectionFactory.setSslContextFactory(name -> sslContext);
  }
  if (virtualHost != null) {
    connectionFactory.setVirtualHost(virtualHost);
  }
  if (brokerHosts.isEmpty()) {
    throw new IllegalArgumentException("No broker host defined");
  }
  return connectionFactory.newConnection(new ArrayList<>(brokerHosts));
}
 
Example 4
Source File: Consumer.java    From rabbitmq-tutorial with MIT License 5 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:guest@localhost");
    factory.setConnectionTimeout(300000);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare("my-queue", true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume("my-queue", false, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

        if (delivery != null) {
            try {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("Message consumed: " + message);
                // Interact with IO
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception e) {
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), true);
            }
        }
    }

}
 
Example 5
Source File: RabbitMqIO.java    From beam with Apache License 2.0 5 votes vote down vote up
public ConnectionHandler(String uri)
    throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
  connectionFactory = new ConnectionFactory();
  connectionFactory.setUri(uri);
  connectionFactory.setAutomaticRecoveryEnabled(true);
  connectionFactory.setConnectionTimeout(60000);
  connectionFactory.setNetworkRecoveryInterval(5000);
  connectionFactory.setRequestedHeartbeat(60);
  connectionFactory.setTopologyRecoveryEnabled(true);
  connectionFactory.setRequestedChannelMax(0);
  connectionFactory.setRequestedFrameMax(0);
}
 
Example 6
Source File: RabbitMQAbstractConfig.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public ConnectionFactory createConnectionFactory() {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost(this.host);
    connectionFactory.setUsername(this.username);
    connectionFactory.setPassword(this.password);
    connectionFactory.setVirtualHost(this.virtualHost);
    connectionFactory.setRequestedChannelMax(this.requestedChannelMax);
    connectionFactory.setRequestedFrameMax(this.requestedFrameMax);
    connectionFactory.setConnectionTimeout(this.connectionTimeout);
    connectionFactory.setHandshakeTimeout(this.handshakeTimeout);
    connectionFactory.setRequestedHeartbeat(this.requestedHeartbeat);
    connectionFactory.setPort(this.port);
    return connectionFactory;
}
 
Example 7
Source File: RabbitMQConnectionFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
private ConnectionFactory from(RabbitMQConfiguration rabbitMQConfiguration) {
    try {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(rabbitMQConfiguration.getUri());
        connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeoutInMs());
        connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeoutInMs());
        connectionFactory.setChannelRpcTimeout(rabbitMQConfiguration.getChannelRpcTimeoutInMs());
        connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeoutInMs());
        connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryIntervalInMs());
        return connectionFactory;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: RabbitMQConnectionFactory.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Initiate rabbitmq connection factory from the connection parameters
 *
 * @param parameters connection parameters
 */
private void initConnectionFactory(Map<String, String> parameters) throws RabbitMQException {
    String hostnames = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_HOST_NAME), ConnectionFactory.DEFAULT_HOST);
    String ports = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_PORT), String.valueOf(ConnectionFactory.DEFAULT_AMQP_PORT));
    String username = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_USER_NAME), ConnectionFactory.DEFAULT_USER);
    String password = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_PASSWORD), ConnectionFactory.DEFAULT_PASS);
    String virtualHost = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST), ConnectionFactory.DEFAULT_VHOST);
    int heartbeat = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.HEARTBEAT), ConnectionFactory.DEFAULT_HEARTBEAT);
    int connectionTimeout = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT), ConnectionFactory.DEFAULT_CONNECTION_TIMEOUT);
    long networkRecoveryInterval = NumberUtils.toLong(
            parameters.get(RabbitMQConstants.NETWORK_RECOVERY_INTERVAL), ConnectionFactory.DEFAULT_NETWORK_RECOVERY_INTERVAL);
    this.retryInterval = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.RETRY_INTERVAL), RabbitMQConstants.DEFAULT_RETRY_INTERVAL);
    this.retryCount = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.RETRY_COUNT), RabbitMQConstants.DEFAULT_RETRY_COUNT);
    boolean sslEnabled = BooleanUtils.toBooleanDefaultIfNull(
            BooleanUtils.toBoolean(parameters.get(RabbitMQConstants.SSL_ENABLED)), false);

    String[] hostnameArray = hostnames.split(",");
    String[] portArray = ports.split(",");
    if (hostnameArray.length == portArray.length) {
        addresses = new Address[hostnameArray.length];
        for (int i = 0; i < hostnameArray.length; i++) {
            try {
                addresses[i] = new Address(hostnameArray[i].trim(), Integer.parseInt(portArray[i].trim()));
            } catch (NumberFormatException e) {
                throw new RabbitMQException("Number format error in port number", e);
            }
        }
    } else {
        throw new RabbitMQException("The number of hostnames must be equal to the number of ports");
    }

    connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setVirtualHost(virtualHost);
    connectionFactory.setRequestedHeartbeat(heartbeat);
    connectionFactory.setConnectionTimeout(connectionTimeout);
    connectionFactory.setNetworkRecoveryInterval(networkRecoveryInterval);
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(true);
    setSSL(parameters, sslEnabled);
}
 
Example 9
Source File: AMQPObservableQueue.java    From conductor with Apache License 2.0 4 votes vote down vote up
private ConnectionFactory buildConnectionFactory() {
	final ConnectionFactory factory = new ConnectionFactory();
	// Get rabbitmq username from config
	final String username = config.getProperty(
			String.format(AMQPConstants.PROPERTY_KEY_TEMPLATE, AMQPConfigurations.PROPERTY_USERNAME),
			ConnectionFactory.DEFAULT_USER);
	if (StringUtils.isEmpty(username)) {
		throw new IllegalArgumentException("Username is null or empty");
	} else {
		factory.setUsername(username);
	}
	// Get rabbitmq password from config
	final String password = config.getProperty(
			String.format(AMQPConstants.PROPERTY_KEY_TEMPLATE, AMQPConfigurations.PROPERTY_PASSWORD),
			ConnectionFactory.DEFAULT_PASS);
	if (StringUtils.isEmpty(password)) {
		throw new IllegalArgumentException("Password is null or empty");
	} else {
		factory.setPassword(password);
	}
	// Get vHost from config
	final String virtualHost = config.getProperty(
			String.format(AMQPConstants.PROPERTY_KEY_TEMPLATE, AMQPConfigurations.PROPERTY_VIRTUAL_HOST),
			ConnectionFactory.DEFAULT_VHOST);
	if (StringUtils.isEmpty(virtualHost)) {
		throw new IllegalArgumentException("Virtual host is null or empty");
	} else {
		factory.setVirtualHost(virtualHost);
	}
	// Get server port from config
	final int port = config.getIntProperty(
			String.format(AMQPConstants.PROPERTY_KEY_TEMPLATE, AMQPConfigurations.PROPERTY_PORT),
			AMQP.PROTOCOL.PORT);
	if (port <= 0) {
		throw new IllegalArgumentException("Port must be greater than 0");
	} else {
		factory.setPort(port);
	}
	// Get connection timeout from config
	final int connectionTimeout = config.getIntProperty(
			String.format(AMQPConstants.PROPERTY_KEY_TEMPLATE, AMQPConfigurations.PROPERTY_CONNECTION_TIMEOUT),
			ConnectionFactory.DEFAULT_CONNECTION_TIMEOUT);
	if (connectionTimeout <= 0) {
		throw new IllegalArgumentException("Connection timeout must be greater than 0");
	} else {
		factory.setConnectionTimeout(connectionTimeout);
	}
	final boolean useNio = config.getBoolProperty(
			String.format(AMQPConstants.PROPERTY_KEY_TEMPLATE, AMQPConfigurations.PROPERTY_USE_NIO), false);
	if (useNio) {
		factory.useNio();
	}
	return factory;
}
 
Example 10
Source File: DefaultChannelFactory.java    From rxrabbit with MIT License 4 votes vote down vote up
private synchronized Connection createConnection(ChannelType connectionType) throws ConnectionFailureException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    settings.getClient_properties().put("connection_type", connectionType.toString());
    settings.getClient_properties().put("connect_time", sdf.format(startTime)+"Z");

    ConnectionFactory cf = new ConnectionFactory();
    cf.setRequestedHeartbeat(settings.getHeartbeat());
    cf.setConnectionTimeout(settings.getConnection_timeout_millis());
    cf.setShutdownTimeout(settings.getShutdown_timeout_millis());
    cf.setRequestedFrameMax(settings.getFrame_max());
    cf.setHandshakeTimeout(settings.getHandshake_timeout_millis());
    cf.setClientProperties((Map)settings.getClient_properties());
    //cf.setSocketConfigurator(); NOTE is this worth investigating??
    cf.setRequestedChannelMax(0);//Hard coded ..
    cf.setAutomaticRecoveryEnabled(false);//Hard coded ..
    cf.setTopologyRecoveryEnabled(false);//Hard coded ..

    Exception lastException = null;
    Connection connection = null;
    for (BrokerAddresses.BrokerAddress address : addresses) {
        cf.setPassword(address.password);
        cf.setUsername(address.username);
        cf.setPort(address.port);
        cf.setHost(address.host);
        cf.setVirtualHost(address.virtualHost);
        try {
            if(address.scheme.toLowerCase().equals("amqps")){
                cf.useSslProtocol();
                cf.setSocketFactory(SSLSocketFactory.getDefault()); //Because rabbit uses NoopTrustStore by default...
            }
            log.infoWithParams("Creating "+connectionType+" connection to broker ...",
                    "address", address.toString(),
                    "settings", settings.toString());
            connection = cf.newConnection();
            boolean isOpen = connection.isOpen();
            if(!isOpen){
                continue;
            }
            break;
        } catch (Exception e) {
            log.debugWithParams("Failed to createConnection to broker",
                    "address", address.toString());
            lastException = e;
        }
    }

    if(connection == null){
        throw new ConnectionFailureException(cf, lastException);
    }

    conToChannel.put(connectionType,
            new ConnectionInfo(
                    connection,
                    new ArrayList<ChannelImpl>(),
                    settings.getClient_properties(),
                    connectionType)
    );
    log.infoWithParams("Successfully created "+connectionType+" connection to broker.",
            "address", addresses.get(0).toString(),
            "localPort", ((AMQConnection) connection).getLocalPort(),
            "settings", settings.toString());

    return connection;

}
 
Example 11
Source File: RabbitMQUtil.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
public static ConnectionFactory getFactory(Context context){
        Preconditions.checkArgument(context!=null, "context cannot be null.");
        ConnectionFactory factory = new ConnectionFactory();
        
        String hostname = context.getString("hostname");
        Preconditions.checkArgument(hostname!=null, "No hostname specified.");
        factory.setHost(hostname);
        
        int port = context.getInteger(RabbitMQConstants.CONFIG_PORT, -1);
        
        if(-1!=port){
            factory.setPort(port);
        }
        
        String username = context.getString(RabbitMQConstants.CONFIG_USERNAME);
        
        if(null==username){
            factory.setUsername(ConnectionFactory.DEFAULT_USER);
        } else {
            factory.setUsername(username);
        }
        
        String password = context.getString(RabbitMQConstants.CONFIG_PASSWORD);
        
        if(null==password){
            factory.setPassword(ConnectionFactory.DEFAULT_PASS);
        } else {
            factory.setPassword(password);
        }
        
        String virtualHost = context.getString(RabbitMQConstants.CONFIG_VIRTUALHOST);
        
        if(null!=virtualHost){
            factory.setVirtualHost(virtualHost);
        }
        
        int connectionTimeout = context.getInteger(RabbitMQConstants.CONFIG_CONNECTIONTIMEOUT, -1);
        
        if(connectionTimeout>-1){
           factory.setConnectionTimeout(connectionTimeout); 
        }
        
        
        
//        boolean useSSL = context.getBoolean("usessl", false);
//        if(useSSL){
//            factory.useSslProtocol();
//        }
        
        
        return factory;
    }
 
Example 12
Source File: ConnectionFactoryProducer.java    From hammock with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
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;
}