List of usage examples for com.rabbitmq.client ConnectionFactory newConnection
public Connection newConnection() throws IOException, TimeoutException
From source file:org.springframework.amqp.rabbit.connection.SSLConnectionTests.java
License:Apache License
@Test @Ignore/*from w w w . j a v a2 s . c o m*/ public void test() throws Exception { RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean(); fb.setUseSSL(true); fb.setSslPropertiesLocation(new ClassPathResource("ssl.properties")); fb.setClientProperties(Collections.<String, Object>singletonMap("foo", "bar")); fb.afterPropertiesSet(); ConnectionFactory cf = fb.getObject(); assertEquals("bar", cf.getClientProperties().get("foo")); Connection conn = cf.newConnection(); Channel chan = conn.createChannel(); chan.close(); conn.close(); }
From source file:org.springframework.amqp.rabbit.core.RabbitAdminIntegrationTests.java
License:Apache License
/** * Verify that a queue exists using the native Rabbit API to bypass all the connection and * channel caching and callbacks in Spring AMQP. * * @param queue The queue to verify/*from w w w. j a va2 s. c om*/ * @return True if the queue exists */ private boolean queueExists(final Queue queue) throws Exception { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); connectionFactory.setPort(BrokerTestUtils.getPort()); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); try { DeclareOk result = channel.queueDeclarePassive(queue.getName()); return result != null; } catch (IOException e) { return e.getCause().getMessage().contains("RESOURCE_LOCKED"); } finally { connection.close(); } }
From source file:org.springframework.amqp.rabbit.junit.BrokerRunning.java
License:Apache License
@Override public Statement apply(Statement base, Description description) { // Check at the beginning, so this can be used as a static field if (this.assumeOnline) { Assume.assumeTrue(brokerOnline.get(this.port)); } else {//from ww w .ja v a 2 s.com Assume.assumeTrue(brokerOffline.get(this.port)); } ConnectionFactory connectionFactory = getConnectionFactory(); Connection connection = null; // NOSONAR (closeResources()) Channel channel = null; try { connection = connectionFactory.newConnection(); connection.setId(generateId()); channel = connection.createChannel(); for (String queueName : this.queues) { if (this.purge) { logger.debug("Deleting queue: " + queueName); // Delete completely - gets rid of consumers and bindings as well channel.queueDelete(queueName); } if (isDefaultQueue(queueName)) { // Just for test probe. channel.queueDelete(queueName); } else { channel.queueDeclare(queueName, true, false, false, null); } } brokerOffline.put(this.port, false); if (!this.assumeOnline) { Assume.assumeTrue(brokerOffline.get(this.port)); } if (this.management) { Client client = new Client(getAdminUri(), this.adminUser, this.adminPassword); if (!client.alivenessTest("/")) { throw new RuntimeException( "Aliveness test failed for localhost:15672 guest/quest; " + "management not available"); } } } catch (Exception e) { logger.warn("Not executing tests because basic connectivity test failed: " + e.getMessage()); brokerOnline.put(this.port, false); if (this.assumeOnline) { if (fatal()) { fail("RabbitMQ Broker is required, but not available"); } else { Assume.assumeNoException(e); } } } finally { closeResources(connection, channel); } return super.apply(base, description); }
From source file:org.springframework.amqp.rabbit.junit.BrokerRunning.java
License:Apache License
/** * Remove any test queues that were created by an * {@link #isRunningWithEmptyQueues(String...)} method. * @param additionalQueues additional queues to remove that might have been created by * tests.//from w w w .ja v a2 s .c o m */ public void removeTestQueues(String... additionalQueues) { List<String> queuesToRemove = Arrays.asList(this.queues); if (additionalQueues != null) { queuesToRemove = new ArrayList<>(queuesToRemove); queuesToRemove.addAll(Arrays.asList(additionalQueues)); } logger.debug("deleting test queues: " + queuesToRemove); ConnectionFactory connectionFactory = getConnectionFactory(); Connection connection = null; // NOSONAR (closeResources()) Channel channel = null; try { connection = connectionFactory.newConnection(); connection.setId(generateId() + ".queueDelete"); channel = connection.createChannel(); for (String queue : queuesToRemove) { channel.queueDelete(queue); } } catch (Exception e) { logger.warn("Failed to delete queues", e); } finally { closeResources(connection, channel); } }
From source file:org.springframework.amqp.rabbit.junit.BrokerRunning.java
License:Apache License
/** * Delete arbitrary queues from the broker. * @param queues the queues to delete./*from w ww .j a v a 2 s .c om*/ */ public void deleteQueues(String... queues) { ConnectionFactory connectionFactory = getConnectionFactory(); Connection connection = null; // NOSONAR (closeResources()) Channel channel = null; try { connection = connectionFactory.newConnection(); connection.setId(generateId() + ".queueDelete"); channel = connection.createChannel(); for (String queue : queues) { channel.queueDelete(queue); } } catch (Exception e) { logger.warn("Failed to delete queues", e); } finally { closeResources(connection, channel); } }
From source file:org.springframework.amqp.rabbit.junit.BrokerRunning.java
License:Apache License
/** * Delete arbitrary exchanges from the broker. * @param exchanges the exchanges to delete. *//*w w w .j a v a 2 s .c o m*/ public void deleteExchanges(String... exchanges) { ConnectionFactory connectionFactory = getConnectionFactory(); Connection connection = null; // NOSONAR (closeResources()) Channel channel = null; try { connection = connectionFactory.newConnection(); connection.setId(generateId() + ".exchangeDelete"); channel = connection.createChannel(); for (String exchange : exchanges) { channel.exchangeDelete(exchange); } } catch (Exception e) { logger.warn("Failed to delete queues", e); } finally { closeResources(connection, channel); } }
From source file:org.springframework.amqp.rabbit.junit.RabbitAvailableTests.java
License:Apache License
@Test public void test(ConnectionFactory connectionFactory) throws Exception { Connection conn = connectionFactory.newConnection(); Channel channel = conn.createChannel(); DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue"); assertEquals(0, declareOk.getConsumerCount()); channel.close();// w w w . ja va2 s.c o m conn.close(); }
From source file:org.springframework.amqp.rabbit.MulticastMain.java
License:Mozilla Public License
public static void main(String[] args) { Options options = getOptions();/*from w w w . j a v a2s .co m*/ CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('?')) { usage(options); System.exit(0); } String hostName = strArg(cmd, 'h', "localhost"); int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT); String exchangeType = strArg(cmd, 't', "direct"); String exchangeName = strArg(cmd, 'e', exchangeType); int samplingInterval = intArg(cmd, 'i', 1); int rateLimit = intArg(cmd, 'r', 0); int producerCount = intArg(cmd, 'x', 1); int messageCount = intArg(cmd, 'N', 0); int consumerCount = intArg(cmd, 'y', 1); int connectionCount = cmd.hasOption('c') ? 1 : consumerCount; int producerTxSize = intArg(cmd, 'm', 0); int consumerTxSize = intArg(cmd, 'n', 0); boolean autoAck = cmd.hasOption('a'); int prefetchCount = intArg(cmd, 'q', 0); int minMsgSize = intArg(cmd, 's', 0); int timeLimit = intArg(cmd, 'z', 0); List<String> flags = lstArg(cmd, 'f'); int frameMax = intArg(cmd, 'M', 0); int heartbeat = intArg(cmd, 'b', 0); // setup String id = UUID.randomUUID().toString(); Stats stats = new Stats(1000L * samplingInterval); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); factory.setPort(portNumber); factory.setRequestedFrameMax(frameMax); factory.setRequestedHeartbeat(heartbeat); Connection[] consumerConnections = new Connection[connectionCount]; for (int i = 0; i < connectionCount; i++) { Connection conn = factory.newConnection(); consumerConnections[i] = conn; } Thread[] consumerThreads = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { System.out.println("starting consumer #" + i); Connection conn = consumerConnections[i % connectionCount]; Channel channel = conn.createChannel(); if (consumerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null) .getQueue(); QueueingConsumer consumer = new QueueingConsumer(channel); if (prefetchCount > 0) channel.basicQos(prefetchCount); channel.basicConsume(queueName, autoAck, consumer); channel.queueBind(queueName, exchangeName, id); Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit)); consumerThreads[i] = t; t.start(); } Thread[] producerThreads = new Thread[producerCount]; Connection[] producerConnections = new Connection[producerCount]; for (int i = 0; i < producerCount; i++) { System.out.println("starting producer #" + i); Connection conn = factory.newConnection(); producerConnections[i] = conn; Channel channel = conn.createChannel(); if (producerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize, 1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount); channel.addReturnListener(p); Thread t = new Thread(p); producerThreads[i] = t; t.start(); } for (int i = 0; i < producerCount; i++) { producerThreads[i].join(); producerConnections[i].close(); } for (int i = 0; i < consumerCount; i++) { consumerThreads[i].join(); } for (int i = 0; i < connectionCount; i++) { consumerConnections[i].close(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); usage(options); } catch (Exception e) { System.err.println("Main thread caught exception: " + e); e.printStackTrace(); System.exit(1); } }
From source file:org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitMqTests.java
License:Apache License
@Test public void shouldConnectUsingRabbitMQClient() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RABBITMQ_HOST);/*from w w w . j a va2s.co m*/ factory.setPort(RABBITMQ_PORT); factory.setUsername(username); factory.setPassword(password); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.close(); connection.close(); }
From source file:org.teksme.server.common.messaging.AMQPBrokerManager.java
License:Apache License
protected Connection connect(MessageMiddleware msgMiddlewareConfig) throws IOException { logger.info("Connecting to AMQP broker..."); ConnectionFactory connFactory = new ConnectionFactory(); connFactory.setUsername(msgMiddlewareConfig.getUsername()); connFactory.setPassword(msgMiddlewareConfig.getPasswd()); connFactory.setVirtualHost(msgMiddlewareConfig.getVirtualHost()); connFactory.setHost(msgMiddlewareConfig.getHost()); connFactory.setRequestedHeartbeat(0); connFactory.setPort(/*from www . j a va 2 s.co m*/ msgMiddlewareConfig.getPort() == null ? AMQP.PROTOCOL.PORT : msgMiddlewareConfig.getPort()); toString(connFactory); try { conn = connFactory.newConnection(); } catch (Exception e) { e.printStackTrace(); } conn.addShutdownListener(this); logger.info("RabbitMQ AMQP broker connected!"); return conn; }