List of usage examples for com.rabbitmq.client ConnectionFactory ConnectionFactory
ConnectionFactory
From source file:org.apache.axis2.transport.rabbitmq.RabbitMQConnectionFactory.java
License:Open Source License
/** * Initialize connection factory/*from ww w . j av a2 s .c om*/ */ private void initConnectionFactory() { connectionFactory = new ConnectionFactory(); String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME); String portValue = parameters.get(RabbitMQConstants.SERVER_PORT); String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL); String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL); String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT); String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT); String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT); String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED); String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME); String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD); String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST); String connectionPoolSizeS = parameters.get(RabbitMQConstants.CONNECTION_POOL_SIZE); if (!StringUtils.isEmpty(heartbeat)) { try { int heartbeatValue = Integer.parseInt(heartbeat); connectionFactory.setRequestedHeartbeat(heartbeatValue); } catch (NumberFormatException e) { //proceeding with rabbitmq default value log.warn("Number format error in reading heartbeat value. Proceeding with default"); } } if (!StringUtils.isEmpty(connectionTimeout)) { try { int connectionTimeoutValue = Integer.parseInt(connectionTimeout); connectionFactory.setConnectionTimeout(connectionTimeoutValue); } catch (NumberFormatException e) { //proceeding with rabbitmq default value log.warn("Number format error in reading connection timeout value. Proceeding with default"); } } if (!StringUtils.isEmpty(connectionPoolSizeS)) { try { connectionPoolSize = Integer.parseInt(connectionPoolSizeS); } catch (NumberFormatException e) { //proceeding with rabbitmq default value log.warn("Number format error in reading connection timeout value. Proceeding with default"); } } if (!StringUtils.isEmpty(sslEnabledS)) { try { boolean sslEnabled = Boolean.parseBoolean(sslEnabledS); if (sslEnabled) { String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION); String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE); String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD); String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION); String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE); String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD); String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION); if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType) || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation) || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) { log.warn( "Trustore and keystore information is not provided correctly. Proceeding with default SSL configuration"); connectionFactory.useSslProtocol(); } else { char[] keyPassphrase = keyStorePassword.toCharArray(); KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(new FileInputStream(keyStoreLocation), keyPassphrase); KeyManagerFactory kmf = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyPassphrase); char[] trustPassphrase = trustStorePassword.toCharArray(); KeyStore tks = KeyStore.getInstance(trustStoreType); tks.load(new FileInputStream(trustStoreLocation), trustPassphrase); TrustManagerFactory tmf = TrustManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); tmf.init(tks); SSLContext c = SSLContext.getInstance(sslVersion); c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); connectionFactory.useSslProtocol(c); } } } catch (Exception e) { log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e); } } if (!StringUtils.isEmpty(retryCountS)) { try { retryCount = Integer.parseInt(retryCountS); } catch (NumberFormatException e) { log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e); } } if (!StringUtils.isEmpty(hostName)) { connectionFactory.setHost(hostName); } else { handleException("Host name is not defined"); } try { int port = Integer.parseInt(portValue); if (port > 0) { connectionFactory.setPort(port); } } catch (NumberFormatException e) { handleException("Number format error in port number", e); } if (!StringUtils.isEmpty(userName)) { connectionFactory.setUsername(userName); } if (!StringUtils.isEmpty(password)) { connectionFactory.setPassword(password); } if (!StringUtils.isEmpty(virtualHost)) { connectionFactory.setVirtualHost(virtualHost); } if (!StringUtils.isEmpty(retryIntervalS)) { try { retryInterval = Integer.parseInt(retryIntervalS); } catch (NumberFormatException e) { log.warn( "Number format error in reading retry interval value. Proceeding with default value (30000ms)", e); } } if (!StringUtils.isEmpty(serverRetryIntervalS)) { try { int serverRetryInterval = Integer.parseInt(serverRetryIntervalS); connectionFactory.setNetworkRecoveryInterval(serverRetryInterval); } catch (NumberFormatException e) { log.warn( "Number format error in reading server retry interval value. Proceeding with default value", e); } } connectionFactory.setAutomaticRecoveryEnabled(true); connectionFactory.setTopologyRecoveryEnabled(false); }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testReadQueue() throws Exception { final int maxNumRecords = 10; PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port) .withQueue("READ").withMaxNumRecords(maxNumRecords)); PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings()) .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8))); List<String> records = generateRecords(maxNumRecords).stream() .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList()); PAssert.that(output).containsInAnyOrder(records); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null;/*from w w w . j av a 2 s . co m*/ try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("READ", false, false, false, null); for (String record : records) { channel.basicPublish("", "READ", null, record.getBytes(StandardCharsets.UTF_8)); } p.run(); } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test(timeout = 60 * 1000) public void testReadExchange() throws Exception { final int maxNumRecords = 10; PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port) .withExchange("READEXCHANGE", "fanout", "test").withMaxNumRecords(maxNumRecords)); PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings()) .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8))); List<String> records = generateRecords(maxNumRecords).stream() .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList()); PAssert.that(output).containsInAnyOrder(records); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null;/*from w w w . java 2 s . com*/ try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare("READEXCHANGE", "fanout"); Channel finalChannel = channel; Thread publisher = new Thread(() -> { try { Thread.sleep(5000); } catch (Exception e) { LOG.error(e.getMessage(), e); } for (int i = 0; i < maxNumRecords; i++) { try { finalChannel.basicPublish("READEXCHANGE", "test", null, ("Test " + i).getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }); publisher.start(); p.run(); publisher.join(); } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testWriteQueue() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream() .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList()); p.apply(Create.of(data))/*from w w w . ja v a2s . c o m*/ .apply(RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("TEST", true, false, false, null); Consumer consumer = new TestConsumer(channel, received); channel.basicConsume("TEST", true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testWriteExchange() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream() .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList()); p.apply(Create.of(data)).apply(/*from www . j a v a 2s .c om*/ RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withExchange("WRITE", "fanout")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare("WRITE", "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, "WRITE", ""); Consumer consumer = new TestConsumer(channel, received); channel.basicConsume(queueName, true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.camel.component.rabbitmq.RabbitMQConsumerIntTest.java
License:Apache License
@Test public void sentMessageIsReceived() throws InterruptedException, IOException { to.expectedMessageCount(1);//w ww. ja v a 2 s . c o m to.expectedHeaderReceived(RabbitMQConstants.REPLY_TO, "myReply"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5672); factory.setUsername("cameltest"); factory.setPassword("cameltest"); factory.setVirtualHost("/"); Connection conn = factory.newConnection(); AMQP.BasicProperties.Builder properties = new AMQP.BasicProperties.Builder(); properties.replyTo("myReply"); Channel channel = conn.createChannel(); channel.basicPublish(EXCHANGE, "", properties.build(), "hello world".getBytes()); to.assertIsSatisfied(); }
From source file:org.apache.camel.component.rabbitmq.RabbitMQProducerIntTest.java
License:Apache License
@Test public void producedMessageIsReceived() throws InterruptedException, IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5672);//w w w .j a v a2 s .c om factory.setUsername("cameltest"); factory.setPassword("cameltest"); factory.setVirtualHost("/"); Connection conn = factory.newConnection(); final List<Envelope> received = new ArrayList<Envelope>(); Channel channel = conn.createChannel(); channel.queueDeclare("sammyq", false, false, true, null); channel.queueBind("sammyq", EXCHANGE, "route1"); channel.basicConsume("sammyq", true, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { received.add(envelope); } }); template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1"); Thread.sleep(500); assertEquals(1, received.size()); }
From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java
License:Apache License
private synchronized Connection createConnection() throws Exception { try {/*from w w w. j a v a2s.c om*/ ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(username); factory.setPassword(password); factory.setVirtualHost("/"); factory.setHost(amqpHost); factory.setPort(port); Connection connection = factory.newConnection(); connection.addShutdownListener(disconnectHandler); _connection = connection; return _connection; } catch (Exception e) { throw e; } }
From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java
License:Apache License
public static void main(String[] args) throws Exception { // We use a List to keep track of option insertion order. See below. final List<Option> optionList = new ArrayList<Option>(); optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h")); optionList.add(OptionBuilder.withLongOpt("hostname").hasArg() .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b")); optionList.add(OptionBuilder.withLongOpt("port").hasArg() .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n")); optionList.add(OptionBuilder.withLongOpt("username").hasArg() .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]") .create("u")); optionList.add(OptionBuilder.withLongOpt("password").hasArg() .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]") .create("p")); optionList.add(OptionBuilder.withLongOpt("vhost").hasArg() .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]") .create("v")); optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg() .withDescription("name of the AMQP exchange [required - no default]").create("e")); optionList.add(OptionBuilder.withLongOpt("key").hasArg() .withDescription("the routing key to use when sending messages [default: 'default.routing.key']") .create("k")); optionList.add(OptionBuilder.withLongOpt("type").hasArg() .withDescription("the type of exchange to create [default: 'topic']").create("t")); optionList.add(OptionBuilder.withLongOpt("durable") .withDescription("if set, a durable exchange will be declared [default: not set]").create("d")); optionList.add(OptionBuilder.withLongOpt("autodelete") .withDescription("if set, an auto-delete exchange will be declared [default: not set]") .create("a")); optionList.add(OptionBuilder.withLongOpt("single") .withDescription("if set, only a single message will be sent [default: not set]").create("s")); optionList.add(OptionBuilder.withLongOpt("start").hasArg() .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]") .create());/*from ww w .ja va2 s.c o m*/ optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription( "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]") .create()); optionList.add(OptionBuilder.withLongOpt("interval").hasArg() .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]") .create()); optionList.add(OptionBuilder.withLongOpt("delay").hasArg() .withDescription("the delay between sending messages in milliseconds [default: 100]").create()); // An extremely silly hack to maintain the above order in the help formatting. HelpFormatter formatter = new HelpFormatter(); // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order. //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments formatter.setOptionComparator((o1, o2) -> { // I know this isn't fast, but who cares! The list is short. //noinspection SuspiciousMethodCalls return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2)); }); // Now we can add all the options to an Options instance. This is dumb! Options options = new Options(); for (Option option : optionList) { options.addOption(option); } CommandLine cmd = null; try { cmd = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("RabbitMQProducerMain", options); System.exit(2); } ConnectionFactory factory = new ConnectionFactory(); if (cmd.hasOption("b")) { factory.setHost(cmd.getOptionValue("b")); } if (cmd.hasOption("u")) { factory.setUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { factory.setPassword(cmd.getOptionValue("p")); } if (cmd.hasOption("v")) { factory.setVirtualHost(cmd.getOptionValue("v")); } if (cmd.hasOption("n")) { factory.setPort(Integer.parseInt(cmd.getOptionValue("n"))); } String exchange = cmd.getOptionValue("e"); String routingKey = "default.routing.key"; if (cmd.hasOption("k")) { routingKey = cmd.getOptionValue("k"); } boolean durable = cmd.hasOption("d"); boolean autoDelete = cmd.hasOption("a"); String type = cmd.getOptionValue("t", "topic"); boolean single = cmd.hasOption("single"); int interval = Integer.parseInt(cmd.getOptionValue("interval", "10")); int delay = Integer.parseInt(cmd.getOptionValue("delay", "100")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date()))); Random r = ThreadLocalRandom.current(); Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00"))); String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}"; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, type, durable, autoDelete, null); do { int wp = (10 + r.nextInt(90)) * 100; String gender = r.nextBoolean() ? "male" : "female"; int age = 20 + r.nextInt(70); String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age); channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line)); System.out.println("Sent message: " + line); timer.add(Calendar.SECOND, interval); Thread.sleep(delay); } while ((!single && stop.after(timer.getTime()))); connection.close(); }
From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java
License:Apache License
/** * * @return Connection Factory for RMQ/*from w w w . j a 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; }