List of usage examples for com.rabbitmq.client ConnectionFactory setTopologyRecoveryEnabled
public void setTopologyRecoveryEnabled(boolean topologyRecovery)
From source file:com.cisco.oss.foundation.message.ChannelWrapper.java
License:Apache License
static void connect() { try {/*from w ww. j a va 2 s . c om*/ Configuration configuration = ConfigurationFactory.getConfiguration(); final Map<String, Map<String, String>> serverConnections = ConfigUtil .parseComplexArrayStructure("service.rabbitmq.connections"); final ArrayList<String> serverConnectionKeys = Lists.newArrayList(serverConnections.keySet()); Collections.sort(serverConnectionKeys); int maxRetryAttempts = configuration.getInt("service.rabbitmq.maxRetryAttempts", 1000); Config config = new Config() .withRecoveryPolicy(new RecoveryPolicy().withBackoff(Duration.seconds(1), Duration.seconds(30)) .withMaxAttempts(maxRetryAttempts)) .withConnectionRecoveryPolicy( new RecoveryPolicy().withBackoff(Duration.seconds(1), Duration.seconds(30)) .withMaxAttempts(maxRetryAttempts)) .withConsumerRecovery(true).withExchangeRecovery(true).withQueueRecovery(true) .withConnectionListeners(new ConnectionListener() { @Override public void onCreate(Connection connection) { LOGGER.trace("connection create: {}", connection); } @Override public void onCreateFailure(Throwable failure) { LOGGER.error("connection create failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecoveryStarted(Connection connection) { LOGGER.trace("connection recovery started: {}", connection); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecovery(Connection connection) { LOGGER.trace("connection recovered: {}", connection); } @Override public void onRecoveryCompleted(Connection connection) { LOGGER.trace("connection recovery completed: {}", connection); IS_CONNECCTION_OR_CHANNEL_UP.set(true); } @Override public void onRecoveryFailure(Connection connection, Throwable failure) { LOGGER.error("connection recovery failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } }).withChannelListeners(new ChannelListener() { @Override public void onCreate(Channel channel) { LOGGER.trace("channel create: {}", channel); } @Override public void onCreateFailure(Throwable failure) { LOGGER.error("channel create failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecoveryStarted(Channel channel) { LOGGER.trace("channel recovery started: {}", channel); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } @Override public void onRecovery(Channel channel) { LOGGER.trace("channel recovered: {}", channel); } @Override public void onRecoveryCompleted(Channel channel) { LOGGER.trace("channel recovery completed: {}", channel); IS_CONNECCTION_OR_CHANNEL_UP.set(true); } @Override public void onRecoveryFailure(Channel channel, Throwable failure) { LOGGER.error("channel recovery failed: {}", failure.toString(), failure); IS_CONNECCTION_OR_CHANNEL_UP.set(false); } }).withConsumerListeners(new ConsumerListener() { @Override public void onRecoveryStarted(Consumer consumer, Channel channel) { LOGGER.trace("consumer create. consumer: {}, channel: {}", consumer, channel); IS_CONSUMER_UP.set(false); } @Override public void onRecoveryCompleted(Consumer consumer, Channel channel) { LOGGER.trace("consumer recovery completed: {}, channel: {}", consumer, channel); IS_CONSUMER_UP.set(true); } @Override public void onRecoveryFailure(Consumer consumer, Channel channel, Throwable failure) { LOGGER.error("consumer recovery failed. consumer: {}, channel: {}, error: {}", consumer, channel, failure.toString(), failure); IS_CONSUMER_UP.set(false); } }); config.getRecoverableExceptions().add(UnknownHostException.class); config.getRecoverableExceptions().add(NoRouteToHostException.class); List<Address> addresses = new ArrayList<>(5); for (String serverConnectionKey : serverConnectionKeys) { Map<String, String> serverConnection = serverConnections.get(serverConnectionKey); String host = serverConnection.get("host"); int port = Integer.parseInt(serverConnection.get("port")); addresses.add(new Address(host, port)); } Address[] addrs = new Address[0]; ConnectionOptions options = new ConnectionOptions().withAddresses(addresses.toArray(addrs)); final ConnectionFactory connectionFactory = options.getConnectionFactory(); connectionFactory.setAutomaticRecoveryEnabled(false); connectionFactory.setTopologyRecoveryEnabled(false); final boolean metricsAndMonitoringIsEnabled = configuration .getBoolean("service.rabbitmq.metricsAndMonitoringJmx.isEnabled", false); if (metricsAndMonitoringIsEnabled) { MetricRegistry registry = new MetricRegistry(); StandardMetricsCollector metrics = new StandardMetricsCollector(registry); connectionFactory.setMetricsCollector(metrics); JmxReporter reporter = JmxReporter.forRegistry(registry).inDomain("com.rabbitmq.client.jmx") .build(); reporter.start(); } final boolean useNio = configuration.getBoolean("service.rabbitmq.useNio", false); if (useNio) { NioParams nioParams = new NioParams(); final Integer nbIoThreads = configuration.getInteger("service.rabbitmq.nio.nbIoThreads", null); final Integer readByteBufferSize = configuration .getInteger("service.rabbitmq.nio.readByteBufferSize", null); final Integer writeByteBufferSize = configuration .getInteger("service.rabbitmq.nio.writeByteBufferSize", null); final Integer writeEnqueuingTimeoutInMs = configuration .getInteger("service.rabbitmq.nio.writeEnqueuingTimeoutInMs", null); final Integer writeQueueCapacity = configuration .getInteger("service.rabbitmq.nio.writeQueueCapacity", null); if (nbIoThreads != null) { nioParams.setNbIoThreads(nbIoThreads); } if (readByteBufferSize != null) { nioParams.setReadByteBufferSize(readByteBufferSize); } if (writeByteBufferSize != null) { nioParams.setWriteByteBufferSize(writeByteBufferSize); } if (writeEnqueuingTimeoutInMs != null) { nioParams.setWriteEnqueuingTimeoutInMs(writeEnqueuingTimeoutInMs); } if (writeQueueCapacity != null) { nioParams.setWriteQueueCapacity(writeQueueCapacity); } // nioParams.setNioExecutor() // nioParams.setThreadFactory() options.withNio().withNioParams(nioParams); } Configuration subsetBase = configuration.subset("service.rabbitmq"); Configuration subsetSecurity = subsetBase.subset("security"); int requestHeartbeat = subsetBase.getInt("requestHeartbeat", 10); options.withRequestedHeartbeat(Duration.seconds(requestHeartbeat)); String userName = subsetSecurity.getString("userName"); String password = subsetSecurity.getString("password"); boolean isEnabled = subsetSecurity.getBoolean("isEnabled"); if (isEnabled) { options.withUsername(userName).withPassword(password); } connection = Connections.create(options, config); connection.addBlockedListener(new BlockedListener() { public void handleBlocked(String reason) throws IOException { LOGGER.error("RabbitMQ connection is now blocked. Port: {}, Reason: {}", connection.getPort(), reason); IS_BLOCKED.set(true); } public void handleUnblocked() throws IOException { LOGGER.info("RabbitMQ connection is now un-blocked. Port: {}", connection.getPort()); IS_BLOCKED.set(false); } }); connection.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { LOGGER.error("Connection shutdown detected. Reason: {}", cause.toString(), cause); IS_CONNECTED.set(false); } }); IS_CONNECTED.set(true); IS_CONNECCTION_OR_CHANNEL_UP.set(true); IS_CONSUMER_UP.set(true); INIT_LATCH.countDown(); } catch (Exception e) { LOGGER.error("can't create RabbitMQ Connection: {}", e, e); // triggerReconnectThread(); throw new QueueException(e); } }
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. */// ww w.j a v a2s.c o 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.novemberain.langohr.Connection.java
License:Open Source License
public Connection(ConnectionFactory cf, IPersistentMap options) { this.cf = cf; this.options = options; Long l = (Long) options.valAt(NETWORK_RECOVERY_DELAY_KEYWORD, DEFAULT_NETWORK_RECOVERY_DELAY); cf.setNetworkRecoveryInterval(l.intValue()); this.automaticallyRecover = Util.isTruthy(options.valAt(AUTOMATICALLY_RECOVER_KEYWORD, true)); this.automaticallyRecoverTopology = Util .isTruthy(options.valAt(AUTOMATICALLY_RECOVER_TOPOLOGY_KEYWORD, true)); cf.setAutomaticRecoveryEnabled(this.automaticallyRecover); cf.setTopologyRecoveryEnabled(this.automaticallyRecoverTopology); }
From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java
License:Apache License
private ConnectionFactory getOrCreateConnectionFactory() { if (connectionFactory == null) { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(getUsername()); factory.setPassword(getPassword()); factory.setVirtualHost(getVhost()); factory.setHost(getHostname());/*from ww w. ja v a 2 s . com*/ factory.setPort(getPortNumber()); if (getClientProperties() != null) { factory.setClientProperties(getClientProperties()); } factory.setConnectionTimeout(getConnectionTimeout()); factory.setRequestedChannelMax(getRequestedChannelMax()); factory.setRequestedFrameMax(getRequestedFrameMax()); factory.setRequestedHeartbeat(getRequestedHeartbeat()); if (getSslProtocol() != null) { try { if (getSslProtocol().equals("true")) { factory.useSslProtocol(); } else if (getTrustManager() == null) { factory.useSslProtocol(getSslProtocol()); } else { factory.useSslProtocol(getSslProtocol(), getTrustManager()); } } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IllegalArgumentException("Invalid sslProtocol " + sslProtocol, e); } } if (getAutomaticRecoveryEnabled() != null) { factory.setAutomaticRecoveryEnabled(getAutomaticRecoveryEnabled()); } if (getNetworkRecoveryInterval() != null) { factory.setNetworkRecoveryInterval(getNetworkRecoveryInterval()); } if (getTopologyRecoveryEnabled() != null) { factory.setTopologyRecoveryEnabled(getTopologyRecoveryEnabled()); } connectionFactory = factory; } return connectionFactory; }
From source file:com.paxxis.cornerstone.messaging.service.amqp.AMQPServiceBusConnector.java
License:Apache License
protected void initConnection() { try {//from w w w. ja v a 2 s. co m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(host); factory.setPort(port); factory.setAutomaticRecoveryEnabled(autoRecover); factory.setConnectionTimeout(timeout); factory.setNetworkRecoveryInterval(recoveryInterval); factory.setRequestedHeartbeat(heartbeat); factory.setTopologyRecoveryEnabled(autoTopologyRecover); factory.setExceptionHandler(exceptionHandler); connection = factory.newConnection(); session = (AMQPSession) createSession(); } catch (IOException e) { logger.error(e); throw new RuntimeException(e); } }
From source file:io.bootique.rabbitmq.client.connection.ConnectionConfig.java
License:Apache License
public Connection createConnection(String connectionName) { com.rabbitmq.client.ConnectionFactory factory = createConnectionFactory(); factory.setRequestedChannelMax(requestedChannelMax); factory.setRequestedFrameMax(requestedFrameMax); factory.setRequestedHeartbeat(requestedHeartbeat); factory.setConnectionTimeout(connectionTimeout); factory.setHandshakeTimeout(handshakeTimeout); factory.setShutdownTimeout(shutdownTimeout); factory.setAutomaticRecoveryEnabled(automaticRecoveryEnabled); factory.setTopologyRecoveryEnabled(topologyRecovery); factory.setNetworkRecoveryInterval(networkRecoveryInterval); LOGGER.info("Creating RabbitMQ connection."); try {//from ww w. j ava2 s . co m return factory.newConnection(); } catch (IOException | TimeoutException e) { throw new RuntimeException(String.format("Can't create connection \"%s\".", connectionName), e); } }
From source file:net.roboconf.messaging.rabbitmq.internal.utils.RabbitMqUtils.java
License:Apache License
/** * Configures the connection factory with the right settings. * @param factory the connection factory * @param configuration the messaging configuration * @throws IOException if something went wrong * @see RabbitMqConstants/*from ww w . ja va2s .c o m*/ */ public static void configureFactory(ConnectionFactory factory, Map<String, String> configuration) throws IOException { final Logger logger = Logger.getLogger(RabbitMqUtils.class.getName()); logger.fine("Configuring a connection factory for RabbitMQ."); String messageServerIp = configuration.get(RABBITMQ_SERVER_IP); if (messageServerIp != null) { Map.Entry<String, Integer> entry = Utils.findUrlAndPort(messageServerIp); factory.setHost(entry.getKey()); if (entry.getValue() > 0) factory.setPort(entry.getValue()); } factory.setUsername(configuration.get(RABBITMQ_SERVER_USERNAME)); factory.setPassword(configuration.get(RABBITMQ_SERVER_PASSWORD)); // Timeout for connection establishment: 5s factory.setConnectionTimeout(5000); // Configure automatic reconnection factory.setAutomaticRecoveryEnabled(true); // Recovery interval: 10s factory.setNetworkRecoveryInterval(10000); // Exchanges and so on should be redeclared if necessary factory.setTopologyRecoveryEnabled(true); // SSL if (Boolean.parseBoolean(configuration.get(RABBITMQ_USE_SSL))) { logger.fine("Connection factory for RabbitMQ: SSL is used."); InputStream clientIS = null; InputStream storeIS = null; try { clientIS = new FileInputStream(configuration.get(RABBITMQ_SSL_KEY_STORE_PATH)); storeIS = new FileInputStream(configuration.get(RABBITMQ_SSL_TRUST_STORE_PATH)); char[] keyStorePassphrase = configuration.get(RABBITMQ_SSL_KEY_STORE_PASSPHRASE).toCharArray(); KeyStore ks = KeyStore.getInstance( getValue(configuration, RABBITMQ_SSL_KEY_STORE_TYPE, DEFAULT_SSL_KEY_STORE_TYPE)); ks.load(clientIS, keyStorePassphrase); String value = getValue(configuration, RABBITMQ_SSL_KEY_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY); KeyManagerFactory kmf = KeyManagerFactory.getInstance(value); kmf.init(ks, keyStorePassphrase); char[] trustStorePassphrase = configuration.get(RABBITMQ_SSL_TRUST_STORE_PASSPHRASE).toCharArray(); KeyStore tks = KeyStore.getInstance( getValue(configuration, RABBITMQ_SSL_TRUST_STORE_TYPE, DEFAULT_SSL_TRUST_STORE_TYPE)); tks.load(storeIS, trustStorePassphrase); value = getValue(configuration, RABBITMQ_SSL_TRUST_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY); TrustManagerFactory tmf = TrustManagerFactory.getInstance(value); tmf.init(tks); SSLContext c = SSLContext .getInstance(getValue(configuration, RABBITMQ_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL)); c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); factory.useSslProtocol(c); } catch (GeneralSecurityException e) { throw new IOException("SSL configuration for the RabbitMQ factory failed.", e); } finally { Utils.closeQuietly(storeIS); Utils.closeQuietly(clientIS); } } }
From source file:org.apache.axis2.transport.rabbitmq.ConnectionFactoryManager.java
License:Open Source License
/** * Get the connection factory that matches the given name, i.e. referring to * the same underlying connection factory. Used by the RabbitMQSender to determine if already * available resources should be used for outgoing messages. If no factory instance is * found then a new one will be created and added to the connection factory map * * @param props a Map of connection factory properties and name * @return the connection factory or null if no connection factory compatible * with the given properties exists */// www . j a v a2 s. c o m public ConnectionFactory getAMQPConnectionFactory(Hashtable<String, String> props) { ConnectionFactory connectionFactory = null; String hostName = props.get(RabbitMQConstants.SERVER_HOST_NAME); String portValue = props.get(RabbitMQConstants.SERVER_PORT); String hostAndPort = hostName + ":" + portValue; connectionFactory = connectionFactories.get(hostAndPort); if (connectionFactory == null) { com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory(); if (hostName != null && !hostName.equals("")) { factory.setHost(hostName); } else { throw new AxisRabbitMQException("Host name is not correctly defined"); } int port = Integer.parseInt(portValue); if (port > 0) { factory.setPort(port); } String userName = props.get(RabbitMQConstants.SERVER_USER_NAME); if (userName != null && !userName.equals("")) { factory.setUsername(userName); } String password = props.get(RabbitMQConstants.SERVER_PASSWORD); if (password != null && !password.equals("")) { factory.setPassword(password); } String virtualHost = props.get(RabbitMQConstants.SERVER_VIRTUAL_HOST); if (virtualHost != null && !virtualHost.equals("")) { factory.setVirtualHost(virtualHost); } factory.setAutomaticRecoveryEnabled(true); factory.setTopologyRecoveryEnabled(false); connectionFactory = new ConnectionFactory(hostAndPort, factory); connectionFactories.put(connectionFactory.getName(), connectionFactory); } return connectionFactory; }
From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java
License:Apache License
/** * * @return Connection Factory for RMQ/*from w w w.ja v a 2 s . c o m*/ * @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.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 w w w . j a v a 2 s . 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(); }