List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateHeaderTests.java
License:Apache License
@Test public void testReplyToOneDeepCustomCorrelationKey() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel); final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); template.setCorrelationKey(CORRELATION_HEADER); Queue replyQueue = new Queue("new.replyTo"); template.setReplyQueue(replyQueue);//from ww w . j a va2 s . c om MessageProperties messageProperties = new MessageProperties(); messageProperties.setReplyTo("replyTo1"); messageProperties.setCorrelationId("saveThis".getBytes()); Message message = new Message("Hello, world!".getBytes(), messageProperties); final AtomicReference<String> replyTo = new AtomicReference<String>(); final AtomicReference<String> correlationId = new AtomicReference<String>(); doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3]; replyTo.set(basicProps.getReplyTo()); correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER)); MessageProperties springProps = new DefaultMessagePropertiesConverter() .toMessageProperties(basicProps, null, "UTF-8"); Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps); template.onMessage(replyMessage); return null; } }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class), Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class)); Message reply = template.sendAndReceive(message); assertNotNull(reply); assertNotNull(replyTo.get()); assertEquals("new.replyTo", replyTo.get()); assertNotNull(correlationId.get()); assertEquals("replyTo1", reply.getMessageProperties().getReplyTo()); assertTrue(!"saveThis".equals(correlationId.get())); assertEquals("replyTo1", reply.getMessageProperties().getReplyTo()); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateHeaderTests.java
License:Apache License
@Test public void testReplyToThreeDeepCustomCorrelationKey() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel); final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); template.setCorrelationKey(CORRELATION_HEADER); Queue replyQueue = new Queue("replyTo2"); template.setReplyQueue(replyQueue);/*from w ww .j av a 2 s .c om*/ MessageProperties messageProperties = new MessageProperties(); messageProperties.setReplyTo("replyTo1"); messageProperties.setCorrelationId("a".getBytes()); Message message = new Message("Hello, world!".getBytes(), messageProperties); final AtomicInteger count = new AtomicInteger(); final List<String> nestedReplyTo = new ArrayList<String>(); final List<String> nestedCorrelation = new ArrayList<String>(); doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3]; nestedReplyTo.add(basicProps.getReplyTo()); nestedCorrelation.add(basicProps.getCorrelationId()); MessageProperties springProps = new DefaultMessagePropertiesConverter() .toMessageProperties(basicProps, null, "UTF-8"); Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps); if (count.incrementAndGet() < 2) { Message anotherMessage = new Message("Second".getBytes(), springProps); template.setReplyQueue(new Queue("replyTo3")); replyMessage = template.sendAndReceive(anotherMessage); nestedReplyTo.add(replyMessage.getMessageProperties().getReplyTo()); nestedCorrelation .add((String) replyMessage.getMessageProperties().getHeaders().get(CORRELATION_HEADER)); } template.onMessage(replyMessage); return null; } }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class), Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class)); Message reply = template.sendAndReceive(message); assertNotNull(reply); assertEquals(3, nestedReplyTo.size()); assertEquals("replyTo2", nestedReplyTo.get(0)); assertEquals("replyTo3", nestedReplyTo.get(1)); assertEquals("replyTo2", nestedReplyTo.get(2)); //intermediate reply assertEquals("replyTo1", reply.getMessageProperties().getReplyTo()); assertEquals("a", new String(reply.getMessageProperties().getCorrelationId(), "UTF-8")); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java
License:Apache License
@Test public void testPublisherConfirmNotReceivedMultiThreads() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); PublisherCallbackChannelImpl channel1 = new PublisherCallbackChannelImpl(mockChannel); PublisherCallbackChannelImpl channel2 = new PublisherCallbackChannelImpl(mockChannel); when(mockConnection.createChannel()).thenReturn(channel1).thenReturn(channel2); final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); final AtomicBoolean confirmed = new AtomicBoolean(); template.setConfirmCallback(new ConfirmCallback() { @Override/* w ww. ja v a2s . c om*/ public void confirm(CorrelationData correlationData, boolean ack, String cause) { confirmed.set(true); } }); // Hold up the first thread so we get two channels final CountDownLatch threadLatch = new CountDownLatch(1); final CountDownLatch threadSentLatch = new CountDownLatch(1); //Thread 1 Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { template.execute(new ChannelCallback<Object>() { @Override public Object doInRabbit(Channel channel) throws Exception { try { threadLatch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } template.doSend(channel, "", ROUTE, new SimpleMessageConverter().toMessage("message", new MessageProperties()), new CorrelationData("def")); threadSentLatch.countDown(); return null; } }); } }); // Thread 2 template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); threadLatch.countDown(); assertTrue(threadSentLatch.await(5, TimeUnit.SECONDS)); Thread.sleep(5); Collection<CorrelationData> unconfirmed = template.getUnconfirmed(0); assertEquals(2, unconfirmed.size()); Set<String> ids = new HashSet<String>(); Iterator<CorrelationData> iterator = unconfirmed.iterator(); ids.add(iterator.next().getId()); ids.add(iterator.next().getId()); assertTrue(ids.remove("abc")); assertTrue(ids.remove("def")); assertFalse(confirmed.get()); DirectFieldAccessor dfa = new DirectFieldAccessor(template); Map<?, ?> pendingConfirms = (Map<?, ?>) dfa.getPropertyValue("pendingConfirms"); assertEquals(2, pendingConfirms.size()); channel1.close(); assertEquals(1, pendingConfirms.size()); channel2.close(); assertEquals(0, pendingConfirms.size()); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java
License:Apache License
@Test public void testPublisherConfirmMultiple() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); PublisherCallbackChannelImpl callbackChannel = new PublisherCallbackChannelImpl(mockChannel); when(mockConnection.createChannel()).thenReturn(callbackChannel); final AtomicInteger count = new AtomicInteger(); doAnswer(new Answer<Object>() { @Override// ww w . ja v a2 s . com public Object answer(InvocationOnMock invocation) throws Throwable { return count.incrementAndGet(); } }).when(mockChannel).getNextPublishSeqNo(); final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); final List<String> confirms = new ArrayList<String>(); final CountDownLatch latch = new CountDownLatch(2); template.setConfirmCallback(new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack) { confirms.add(correlationData.getId()); latch.countDown(); } } }); template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def")); callbackChannel.handleAck(2, true); assertTrue(latch.await(1000, TimeUnit.MILLISECONDS)); Collection<CorrelationData> unconfirmed = template.getUnconfirmed(0); assertNull(unconfirmed); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java
License:Apache License
/** * Tests that piggy-backed confirms (multiple=true) are distributed to the proper * template.//from ww w. ja va 2 s . co m * @throws Exception */ @Test public void testPublisherConfirmMultipleWithTwoListeners() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); PublisherCallbackChannelImpl callbackChannel = new PublisherCallbackChannelImpl(mockChannel); when(mockConnection.createChannel()).thenReturn(callbackChannel); final AtomicInteger count = new AtomicInteger(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return count.incrementAndGet(); } }).when(mockChannel).getNextPublishSeqNo(); final RabbitTemplate template1 = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); final Set<String> confirms = new HashSet<String>(); final CountDownLatch latch1 = new CountDownLatch(1); template1.setConfirmCallback(new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack) { confirms.add(correlationData.getId() + "1"); latch1.countDown(); } } }); final RabbitTemplate template2 = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); final CountDownLatch latch2 = new CountDownLatch(1); template2.setConfirmCallback(new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack) { confirms.add(correlationData.getId() + "2"); latch2.countDown(); } } }); template1.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); template2.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def")); template2.convertAndSend(ROUTE, (Object) "message", new CorrelationData("ghi")); callbackChannel.handleAck(3, true); assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS)); assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS)); Collection<CorrelationData> unconfirmed1 = template1.getUnconfirmed(0); assertNull(unconfirmed1); Collection<CorrelationData> unconfirmed2 = template2.getUnconfirmed(0); assertNull(unconfirmed2); assertTrue(confirms.contains("abc1")); assertTrue(confirms.contains("def2")); assertTrue(confirms.contains("ghi2")); assertEquals(3, confirms.size()); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java
License:Apache License
/** * AMQP-262//from w w w .j a v a 2 s . c o m * Sets up a situation where we are processing 'multi' acks at the same * time as adding a new pending ack to the map. Test verifies we don't * get a {@link ConcurrentModificationException}. */ @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" }) @Test public void testConcurrentConfirms() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockChannel.getNextPublishSeqNo()).thenReturn(1L, 2L, 3L, 4L); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); final PublisherCallbackChannelImpl channel = new PublisherCallbackChannelImpl(mockChannel); when(mockConnection.createChannel()).thenReturn(channel); final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); final CountDownLatch first2SentOnThread1Latch = new CountDownLatch(1); final CountDownLatch delayAckProcessingLatch = new CountDownLatch(1); final CountDownLatch startedProcessingMultiAcksLatch = new CountDownLatch(1); final CountDownLatch waitForAll3AcksLatch = new CountDownLatch(3); final CountDownLatch allSentLatch = new CountDownLatch(1); final AtomicInteger acks = new AtomicInteger(); template.setConfirmCallback(new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { try { startedProcessingMultiAcksLatch.countDown(); // delay processing here; ensures thread 2 put would be concurrent delayAckProcessingLatch.await(2, TimeUnit.SECONDS); // only delay first time through delayAckProcessingLatch.countDown(); waitForAll3AcksLatch.countDown(); acks.incrementAndGet(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def")); first2SentOnThread1Latch.countDown(); } }); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { try { startedProcessingMultiAcksLatch.await(); template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("ghi")); allSentLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); assertTrue(first2SentOnThread1Latch.await(10, TimeUnit.SECONDS)); // there should be no concurrent execution exception here channel.handleAck(2, true); assertTrue(allSentLatch.await(10, TimeUnit.SECONDS)); channel.handleAck(3, false); assertTrue(waitForAll3AcksLatch.await(10, TimeUnit.SECONDS)); assertEquals(3, acks.get()); // 3.3.1 client channel.basicConsume("foo", false, (Map) null, (Consumer) null); verify(mockChannel).basicConsume("foo", false, (Map) null, (Consumer) null); channel.basicQos(3, false); verify(mockChannel).basicQos(3, false); doReturn(true).when(mockChannel).flowBlocked(); assertTrue(channel.flowBlocked()); try { channel.flow(true); fail("Expected exception"); } catch (UnsupportedOperationException e) { } try { channel.getFlow(); fail("Expected exception"); } catch (UnsupportedOperationException e) { } // 3.2.4 client /* try { channel.basicConsume("foo", false, (Map) null, (Consumer) null); fail("Expected exception"); } catch (UnsupportedOperationException e) {} try { channel.basicQos(3, false); fail("Expected exception"); } catch (UnsupportedOperationException e) {} try { channel.flowBlocked(); fail("Expected exception"); } catch (UnsupportedOperationException e) {} channel.flow(true); verify(mockChannel).flow(true); channel.getFlow(); verify(mockChannel).getFlow(); */ }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateTests.java
License:Apache License
@Test public void returnConnectionAfterCommit() throws Exception { @SuppressWarnings("serial") TransactionTemplate txTemplate = new TransactionTemplate(new AbstractPlatformTransactionManager() { @Override//from ww w. j a v a 2 s .c o m protected Object doGetTransaction() throws TransactionException { return new Object(); } @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { } @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException { } @Override protected void doRollback(DefaultTransactionStatus status) throws TransactionException { } }); ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel); when(mockChannel.isOpen()).thenReturn(true); final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory(mockConnectionFactory)); template.setChannelTransacted(true); txTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { template.convertAndSend("foo", "bar"); return null; } }); txTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { template.convertAndSend("baz", "qux"); return null; } }); verify(mockConnectionFactory, Mockito.times(1)).newConnection(Mockito.any(ExecutorService.class)); // ensure we used the same channel verify(mockConnection, Mockito.times(1)).createChannel(); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateTests.java
License:Apache License
@SuppressWarnings("unchecked") @Test // AMQP-249 public void dontHangConsumerThread() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel); when(mockChannel.queueDeclare()).thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0)); final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>(); doAnswer(new Answer<Object>() { @Override/*from ww w . j a v a 2s. co m*/ public Object answer(InvocationOnMock invocation) throws Throwable { consumer.set((Consumer) invocation.getArguments()[6]); return null; } }).when(mockChannel).basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyMap(), Mockito.any(Consumer.class)); RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory)); template.setReplyTimeout(1); Message input = new Message("Hello, world!".getBytes(), new MessageProperties()); template.doSendAndReceiveWithTemporary("foo", "bar", input); Envelope envelope = new Envelope(1, false, "foo", "bar"); // used to hang here because of the SynchronousQueue and doSendAndReceive() already exited consumer.get().handleDelivery("foo", envelope, new AMQP.BasicProperties(), new byte[0]); }
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 {// ww w.java 2 s. c o m 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./* ww w . ja v a 2s . 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); } }