List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
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./* w w w. j ava 2s .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. *//*from 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.RabbitAvailableCTORInjectionTests.java
License:Apache License
@Test public void test(ConnectionFactory cf) throws Exception { assertSame(cf, this.connectionFactory); Connection conn = this.connectionFactory.newConnection(); Channel channel = conn.createChannel(); DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue"); assertEquals(0, declareOk.getConsumerCount()); channel.close();/*from w w w . j av a 2s. c o m*/ conn.close(); }
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();/*from w w w.j av a 2 s . co m*/ conn.close(); }
From source file:org.springframework.amqp.rabbit.listener.ExternalTxManagerTests.java
License:Apache License
/** * Verifies that an up-stack RabbitTemplate does not use the listener's * channel when it has its own connection factory. *//*w w w . j a v a 2 s.co m*/ @SuppressWarnings("unchecked") @Test public void testMessageListenerTemplateUsesDifferentConnectionFactory() throws Exception { ConnectionFactory listenerConnectionFactory = mock(ConnectionFactory.class); ConnectionFactory templateConnectionFactory = mock(ConnectionFactory.class); Connection listenerConnection = mock(Connection.class); Connection templateConnection = mock(Connection.class); final Channel listenerChannel = mock(Channel.class); Channel templateChannel = mock(Channel.class); when(listenerChannel.isOpen()).thenReturn(true); when(templateChannel.isOpen()).thenReturn(true); final CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory( listenerConnectionFactory); final CachingConnectionFactory cachingTemplateConnectionFactory = new CachingConnectionFactory( templateConnectionFactory); when(listenerConnectionFactory.newConnection((ExecutorService) null)).thenReturn(listenerConnection); when(listenerConnection.isOpen()).thenReturn(true); when(templateConnectionFactory.newConnection((ExecutorService) null)).thenReturn(templateConnection); when(templateConnection.isOpen()).thenReturn(true); when(templateConnection.createChannel()).thenReturn(templateChannel); final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>(); doAnswer(new Answer<Channel>() { boolean done; @Override public Channel answer(InvocationOnMock invocation) throws Throwable { if (!done) { done = true; return listenerChannel; } tooManyChannels.set(new Exception("More than one channel requested")); Channel channel = mock(Channel.class); when(channel.isOpen()).thenReturn(true); return channel; } }).when(listenerConnection).createChannel(); final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>(); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { consumer.set((Consumer) invocation.getArguments()[6]); return null; } }).when(listenerChannel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); final CountDownLatch commitLatch = new CountDownLatch(2); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { commitLatch.countDown(); return null; } }).when(listenerChannel).txCommit(); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { commitLatch.countDown(); return null; } }).when(templateChannel).txCommit(); final CountDownLatch latch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory); container.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingTemplateConnectionFactory); rabbitTemplate.setChannelTransacted(true); // should use same channel as container rabbitTemplate.convertAndSend("foo", "bar", "baz"); latch.countDown(); } }); container.setQueueNames("queue"); container.setChannelTransacted(true); container.setShutdownTimeout(100); container.setTransactionManager(new DummyTxManager()); container.afterPropertiesSet(); container.start(); consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] { 0 }); assertTrue(latch.await(10, TimeUnit.SECONDS)); Exception e = tooManyChannels.get(); if (e != null) { throw e; } verify(listenerConnection, Mockito.times(1)).createChannel(); verify(templateConnection, Mockito.times(1)).createChannel(); assertTrue(commitLatch.await(10, TimeUnit.SECONDS)); verify(listenerChannel).txCommit(); verify(templateChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class)); verify(templateChannel).txCommit(); // verify close() was never called on the channel DirectFieldAccessor dfa = new DirectFieldAccessor(cachingConnectionFactory); List<?> channels = (List<?>) dfa.getPropertyValue("cachedChannelsTransactional"); assertEquals(0, channels.size()); container.stop(); }
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 va 2s.com 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);//w w w . j a v a2 s .c om 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 void declareQueueing(Connection conn, MessageMiddleware config) throws IOException { String routingKey = null;/*from w w w .j av a 2 s. c o m*/ String exchangeName = null; String queueName = null; String type = null; boolean durable = false; boolean autoDelete = false; boolean exclusive = false; List<MessageMiddleware.Queue> queues = config.getQueues(); for (Queue queue : queues) { queueName = queue.getName(); routingKey = queue.getKey(); exchangeName = queue.getExchange(); type = queue.getType(); durable = queue.isDurable(); autoDelete = queue.isAutoDelete(); exclusive = queue.isExclusive(); logger.info("Declaring exchange [" + exchangeName + "] and queue [" + queueName + "]"); Channel channel = conn.createChannel(); channel.exchangeDeclare(exchangeName, type, durable); channel.queueDeclare(queueName, durable, exclusive, autoDelete, null); logger.info("Binding queue [" + queueName + "] and exchange [" + exchangeName + "] to routing key [" + routingKey + "]"); channel.queueBind(queueName, exchangeName, routingKey); } }
From source file:org.teksme.server.queue.consumer.impl.ChannelTracker.java
License:Apache License
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override//from w w w . j av a 2 s . c o m public Map<Channel, String> addingService(ServiceReference reference) { Connection conn = (Connection) context.getService(reference); String consumerTag = null; Map<Channel, String> registry = new HashMap<Channel, String>(); Channel channel = null; try { XmlConfiguration read = new XmlConfiguration(); TeksConfig.MessageMiddleware config = read.readMessageMiddlewareConfig("teks-server.xml"); String queueName = null; List<MessageMiddleware.Queue> queues = config.getQueues(); for (Queue queue : queues) { queueName = queue.getName(); logger.info("Declaring basic MQ consumer for queue: " + queueName); channel = conn.createChannel(); // ensure you never have more than 100 messages queued up in the // consumer channel.basicQos(100); Class consumerClazz; consumerClazz = Class.forName(queue.getConsumerClass()); Constructor constructor = consumerClazz.getConstructor(Channel.class); BaseConsumer consumer = (BaseConsumer) constructor.newInstance(channel); // OutboundMessageConsumer consumer = new // OutboundMessageConsumer(channel); consumer.addMessageListener(new OutboundSMSHandler()); consumerTag = channel.basicConsume(queueName, consumer); registry.put(channel, consumerTag); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return null; } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return registry; }
From source file:org.teksme.server.queue.sender.impl.AMQPQueueSenderService.java
License:Apache License
public void publishMessage(OutboundMessage outboundMsg) { Channel lChannel = null;//from w ww . j a v a2 s . c om Connection lConnection = null; try { lConnection = getAMQPConnServiceReference(); lChannel = lConnection.createChannel(); byte[] data = convertToSend(outboundMsg); // Parameters to constructor for new AMQP.BasicProperties are: // (contentType, contentEncoding, headers, deliveryMode, priority, // correlationId, replyTo, expiration, messageId, timestamp, // type, userId, appId, clusterId) // http://www.rabbitmq.com/releases/rabbitmq-java-client/v2.1.0/rabbitmq-java-client-javadoc-2.1.0/ final String contentType = "text/xml"; final String contentEncoding = null;// outboundMsg.getEncoding(0); final Integer PERSISTENT = 2; final Integer deliveryMode = PERSISTENT; final Integer priority = null; // outboundMsg.getDeliveryQueuePriority(0); final String replyTo = outboundMsg.getFrom(); final String expiration = Float.toString(outboundMsg.getTimeout()); final String messageId = outboundMsg.getId(); final Date timestamp = outboundMsg.getDate(); AMQP.BasicProperties messageProps = new AMQP.BasicProperties(contentType, contentEncoding, null, deliveryMode, priority, null, replyTo, expiration, messageId, timestamp, null, null, null, null); final String queueName = "teksme.outboundPrimaryQueue"; final String routingKey = "sms.outbound"; final String exchange = "teksme.outbound"; logger.info( "Publishing message to queue [" + queueName + "] with routing key [" + routingKey + "] ..."); lChannel.basicPublish(exchange, routingKey, messageProps, data); // new Test().run(); } catch (InvalidSyntaxException e) { // Shouldn't happen e.printStackTrace(); } catch (Exception lIoException) { throw new RuntimeException(lIoException); } finally { try { closeChannel(lChannel); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }