List of usage examples for com.rabbitmq.client Address Address
public Address(String host, int port)
From source file:com.avricot.avrilog.rabbitmq.HaConnectionFactory.java
License:Apache License
public HaConnectionFactory(final String connectionUrl) { super();//from www. j a va 2 s. co m ArrayList<Address> adds = new ArrayList<Address>(); if (connectionUrl != null) { String[] urls = connectionUrl.split(","); for (String url : urls) { String host = url.substring(0, url.indexOf(":")); String port = url.substring(url.indexOf(":") + 1); adds.add(new Address(host, Integer.valueOf(port))); LOG.info("rabbitmq node address : {}:{}", host, port); } addresses = adds.toArray(new Address[adds.size()]); } else { LOG.info("rabbitmq node address set to default"); addresses = null; } }
From source file:com.cisco.oss.foundation.message.ChannelWrapper.java
License:Apache License
static void connect() { try {/*from w w w . j a v a2 s . co m*/ 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.github.larsq.spring.embeddedamqp.SimpleAmqpConnectionFactory.java
License:Open Source License
@Override public Connection newConnection() throws IOException { return new ConnectionImpl(new Address(getHost(), getPort()), this); //To change body of generated methods, choose Tools | Templates. }
From source file:cs.karibu.helloworld.stage2.ExampleExchangeConfiguration.java
License:Apache License
@Override public Address[] getServerAddressList() { // the default port is 5672, and the 'cluster' is a single machine Address[] clusterAddr = new Address[] { new Address(mqServerName, 5672) }; return clusterAddr; }
From source file:dk.au.cs.karibu.producer.rabbitmq.StandardRabbitExchangeConfiguration.java
License:Apache License
/** * Constructs a <code>StandardRabbitExchangeConfiguration</code>. * /* w w w. ja v a2 s . c o m*/ * @param exchangeProperties */ public StandardRabbitExchangeConfiguration(Properties exchangeProperties) { String username = FailFast.readProperty(exchangeProperties, USERNAME); String password = FailFast.readProperty(exchangeProperties, PASSWORD); boolean sslConnection = FailFast.readProperty(exchangeProperties, SSL_CONNECTION).equalsIgnoreCase("true"); String exchangeName = FailFast.readProperty(exchangeProperties, EXCHANGE_NAME); boolean exchangeDurable = FailFast.readProperty(exchangeProperties, EXCHANGE_DURABLE) .equalsIgnoreCase("true"); String exchangeType = FailFast.readProperty(exchangeProperties, EXCHANGE_TYPE); String addressString = FailFast.readProperty(exchangeProperties, SERVER_ADDRESS_LIST); String[] addressStrings = addressString.split(","); List<Address> addresses = new ArrayList<Address>(5); for (String address : addressStrings) { String[] splitAddress = address.split(":"); String host = splitAddress[0]; int port = 5672; if (sslConnection) { port = 5671; } if (splitAddress.length > 1) { try { port = Integer.parseInt(splitAddress[1]); } catch (Exception e) { Logger log = LoggerFactory.getLogger(StandardRabbitExchangeConfiguration.class); log.error("Integer parsing error on port number from address property", e); System.out.println("Port number error in property file, review the log..."); // Fail fast, no need to carry on before the property file has been fixed. System.exit(-1); } } addresses.add(new Address(host, port)); } Address[] serverAddressList = addresses.toArray(new Address[0]); init(username, password, serverAddressList, sslConnection, exchangeName, exchangeDurable, exchangeType); }
From source file:gemlite.core.internal.mq.receiver.rabbit.RabbitMqReceiver.java
License:Apache License
protected void initRecv() { checkWorkable();/* w w w . jav a 2s . co m*/ String[] hpArr = getParam().getHostsAndPorts().split(","); address = new Address[hpArr.length]; for (int i = 0; i < address.length; i++) { address[i] = new Address(hpArr[i].split(":")[0], Integer.parseInt(hpArr[i].split(":")[1])); } factory = new ConnectionFactory(); factory.setUsername(getParam().getUserName()); factory.setPassword(getParam().getPassward()); factory.setVirtualHost(getParam().getVhost()); try { createConnect(); } catch (IOException e) { LogUtil.getMqSyncLog().error("Create connect failure.", e); } LogUtil.getMqSyncLog().info(" Connection and Channel Create Complete. "); }
From source file:org.apache.camel.component.rabbitmq.RabbitMQEndpointTest.java
License:Apache License
@Test public void brokerEndpointAddressesSettings() throws Exception { RabbitMQEndpoint endpoint = context.getEndpoint( "rabbitmq:localhost/exchange?addresses=server1:12345,server2:12345", RabbitMQEndpoint.class); assertEquals("Wrong size of endpoint addresses.", 2, endpoint.getAddresses().length); assertEquals("Get a wrong endpoint address.", new Address("server1", 12345), endpoint.getAddresses()[0]); assertEquals("Get a wrong endpoint address.", new Address("server2", 12345), endpoint.getAddresses()[1]); }
From source file:org.apache.james.backend.rabbitmq.DockerRabbitMQ.java
License:Apache License
public Address address() { return new Address(getHostIp(), getPort()); }
From source file:org.apache.synapse.transport.amqp.AMQPTransportUtils.java
License:Apache License
/** * Digest the address array in the form hostName1:portNumber1,hostName2:portNumber2,hostName3:portNumber3 * * @param addressString Address array string * @param regex the first regex to split the string * @param subRegex the sub regex to split the string * @return the address array// w ww . j a v a 2s . c o m * @throws NumberFormatException in case an invalid port. */ public static Address[] getAddressArray(String addressString, final String regex, final char subRegex) throws NumberFormatException { String[] hosts = addressString.split(regex); Address[] addresses = new Address[hosts.length]; for (int i = 0; i < hosts.length; i++) { addresses[i] = new Address(hosts[i].substring(0, hosts[i].indexOf(subRegex)), Integer.parseInt(hosts[i].substring(hosts[i].indexOf(subRegex) + 1))); } return addresses; }
From source file:org.elasticsearch.river.rabbitmq.RabbitmqRiver.java
License:Apache License
@SuppressWarnings({ "unchecked" }) @Inject// w ww . j a va 2 s . c o m public RabbitmqRiver(RiverName riverName, RiverSettings settings, Client client, ScriptService scriptService) { super(riverName, settings); this.client = client; if (settings.settings().containsKey("rabbitmq")) { Map<String, Object> rabbitSettings = (Map<String, Object>) settings.settings().get("rabbitmq"); if (rabbitSettings.containsKey("addresses")) { List<Address> addresses = new ArrayList<Address>(); for (Map<String, Object> address : (List<Map<String, Object>>) rabbitSettings.get("addresses")) { addresses.add(new Address(XContentMapValues.nodeStringValue(address.get("host"), "localhost"), XContentMapValues.nodeIntegerValue(address.get("port"), AMQP.PROTOCOL.PORT))); } rabbitAddresses = addresses.toArray(new Address[addresses.size()]); } else { String rabbitHost = XContentMapValues.nodeStringValue(rabbitSettings.get("host"), "localhost"); int rabbitPort = XContentMapValues.nodeIntegerValue(rabbitSettings.get("port"), AMQP.PROTOCOL.PORT); rabbitAddresses = new Address[] { new Address(rabbitHost, rabbitPort) }; } rabbitUser = XContentMapValues.nodeStringValue(rabbitSettings.get("user"), "guest"); rabbitPassword = XContentMapValues.nodeStringValue(rabbitSettings.get("pass"), "guest"); rabbitVhost = XContentMapValues.nodeStringValue(rabbitSettings.get("vhost"), "/"); rabbitQueue = XContentMapValues.nodeStringValue(rabbitSettings.get("queue"), "elasticsearch"); rabbitExchange = XContentMapValues.nodeStringValue(rabbitSettings.get("exchange"), "elasticsearch"); rabbitRoutingKey = XContentMapValues.nodeStringValue(rabbitSettings.get("routing_key"), "elasticsearch"); rabbitExchangeDeclare = XContentMapValues.nodeBooleanValue(rabbitSettings.get("exchange_declare"), true); if (rabbitExchangeDeclare) { rabbitExchangeType = XContentMapValues.nodeStringValue(rabbitSettings.get("exchange_type"), "direct"); rabbitExchangeDurable = XContentMapValues.nodeBooleanValue(rabbitSettings.get("exchange_durable"), true); } else { rabbitExchangeType = "direct"; rabbitExchangeDurable = true; } rabbitQueueDeclare = XContentMapValues.nodeBooleanValue(rabbitSettings.get("queue_declare"), true); if (rabbitQueueDeclare) { rabbitQueueDurable = XContentMapValues.nodeBooleanValue(rabbitSettings.get("queue_durable"), true); rabbitQueueAutoDelete = XContentMapValues.nodeBooleanValue(rabbitSettings.get("queue_auto_delete"), false); if (rabbitSettings.containsKey("args")) { rabbitQueueArgs = (Map<String, Object>) rabbitSettings.get("args"); } } else { rabbitQueueDurable = true; rabbitQueueAutoDelete = false; } rabbitQueueBind = XContentMapValues.nodeBooleanValue(rabbitSettings.get("queue_bind"), true); rabbitHeartbeat = TimeValue.parseTimeValue( XContentMapValues.nodeStringValue(rabbitSettings.get("heartbeat"), "30m"), TimeValue.timeValueMinutes(30)); } else { rabbitAddresses = new Address[] { new Address("localhost", AMQP.PROTOCOL.PORT) }; rabbitUser = "guest"; rabbitPassword = "guest"; rabbitVhost = "/"; rabbitQueue = "elasticsearch"; rabbitQueueAutoDelete = false; rabbitQueueDurable = true; rabbitExchange = "elasticsearch"; rabbitExchangeType = "direct"; rabbitExchangeDurable = true; rabbitRoutingKey = "elasticsearch"; rabbitExchangeDeclare = true; rabbitQueueDeclare = true; rabbitQueueBind = true; rabbitHeartbeat = TimeValue.timeValueMinutes(30); } if (settings.settings().containsKey("index")) { Map<String, Object> indexSettings = (Map<String, Object>) settings.settings().get("index"); bulkSize = XContentMapValues.nodeIntegerValue(indexSettings.get("bulk_size"), 100); if (indexSettings.containsKey("bulk_timeout")) { bulkTimeout = TimeValue.parseTimeValue( XContentMapValues.nodeStringValue(indexSettings.get("bulk_timeout"), "10ms"), TimeValue.timeValueMillis(10)); } else { bulkTimeout = TimeValue.timeValueMillis(10); } ordered = XContentMapValues.nodeBooleanValue(indexSettings.get("ordered"), false); } else { bulkSize = 100; bulkTimeout = TimeValue.timeValueMillis(10); ordered = false; } if (settings.settings().containsKey("bulk_script_filter")) { Map<String, Object> scriptSettings = (Map<String, Object>) settings.settings() .get("bulk_script_filter"); if (scriptSettings.containsKey("script")) { String scriptLang = "native"; if (scriptSettings.containsKey("script_lang")) { scriptLang = scriptSettings.get("script_lang").toString(); } Map<String, Object> scriptParams = null; if (scriptSettings.containsKey("script_params")) { scriptParams = (Map<String, Object>) scriptSettings.get("script_params"); } else { scriptParams = Maps.newHashMap(); } bulkScript = scriptService.executable(scriptLang, scriptSettings.get("script").toString(), scriptParams); } else { bulkScript = null; } } else { bulkScript = null; } if (settings.settings().containsKey("script_filter")) { Map<String, Object> scriptSettings = (Map<String, Object>) settings.settings().get("script_filter"); if (scriptSettings.containsKey("script")) { String scriptLang = "mvel"; if (scriptSettings.containsKey("script_lang")) { scriptLang = scriptSettings.get("script_lang").toString(); } Map<String, Object> scriptParams = null; if (scriptSettings.containsKey("script_params")) { scriptParams = (Map<String, Object>) scriptSettings.get("script_params"); } else { scriptParams = Maps.newHashMap(); } script = scriptService.executable(scriptLang, scriptSettings.get("script").toString(), scriptParams); } else { script = null; } } else { script = null; } }