List of usage examples for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer SimpleMessageListenerContainer
public SimpleMessageListenerContainer(ConnectionFactory connectionFactory)
From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java
@Test public void testCompressionWithContainer() throws Exception { final List<Message> received = new ArrayList<Message>(); final CountDownLatch latch = new CountDownLatch(2); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory); container.setQueueNames(ROUTE);/*from w ww . ja v a 2 s. c om*/ container.setMessageListener((MessageListener) message -> { received.add(message); latch.countDown(); }); container.setReceiveTimeout(100); container.setAfterReceivePostProcessors(new DelegatingDecompressingPostProcessor()); container.afterPropertiesSet(); container.start(); try { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(2, Integer.MAX_VALUE, 30000); BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler); template.setConnectionFactory(this.connectionFactory); template.setBeforePublishPostProcessors(new GZipPostProcessor()); MessageProperties props = new MessageProperties(); Message message = new Message("foo".getBytes(), props); template.send("", ROUTE, message); message = new Message("bar".getBytes(), props); template.send("", ROUTE, message); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertEquals(2, received.size()); assertEquals("foo", new String(received.get(0).getBody())); assertEquals(3, received.get(0).getMessageProperties().getContentLength()); assertEquals("bar", new String(received.get(1).getBody())); assertEquals(3, received.get(0).getMessageProperties().getContentLength()); } finally { container.stop(); } }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java
@Test public void testPublisherConfirmWithSendAndReceive() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<CorrelationData> confirmCD = new AtomicReference<CorrelationData>(); templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> { confirmCD.set(correlationData);/* w ww . j a v a 2 s .c om*/ latch.countDown(); }); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer( this.connectionFactoryWithConfirmsEnabled); container.setQueueNames(ROUTE); container.setMessageListener( new MessageListenerAdapter((ReplyingMessageListener<String, String>) String::toUpperCase)); container.start(); CorrelationData correlationData = new CorrelationData("abc"); String result = (String) this.templateWithConfirmsEnabled.convertSendAndReceive(ROUTE, (Object) "message", correlationData); container.stop(); assertEquals("MESSAGE", result); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertEquals(correlationData, confirmCD.get()); }
From source file:org.springframework.amqp.rabbit.listener.MessageListenerContainerMultipleQueueIntegrationTests.java
private void doTest(int concurrentConsumers, ContainerConfigurer configurer) { int messageCount = 10; RabbitTemplate template = new RabbitTemplate(); CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setChannelCacheSize(concurrentConsumers); connectionFactory.setPort(BrokerTestUtils.getPort()); template.setConnectionFactory(connectionFactory); SimpleMessageConverter messageConverter = new SimpleMessageConverter(); messageConverter.setCreateMessageIds(true); template.setMessageConverter(messageConverter); for (int i = 0; i < messageCount; i++) { template.convertAndSend(queue1.getName(), new Integer(i)); template.convertAndSend(queue2.getName(), new Integer(i)); }//from ww w. j av a 2 s. c o m final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); final CountDownLatch latch = new CountDownLatch(messageCount * 2); PojoListener listener = new PojoListener(latch); container.setMessageListener(new MessageListenerAdapter(listener)); container.setAcknowledgeMode(AcknowledgeMode.AUTO); container.setChannelTransacted(true); container.setConcurrentConsumers(concurrentConsumers); configurer.configure(container); container.afterPropertiesSet(); container.start(); try { int timeout = Math.min(1 + messageCount / concurrentConsumers, 30); boolean waited = latch.await(timeout, TimeUnit.SECONDS); logger.info("All messages recovered: " + waited); assertEquals(concurrentConsumers, container.getActiveConsumerCount()); assertTrue("Timed out waiting for messages", waited); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("unexpected interruption"); } finally { container.shutdown(); assertEquals(0, container.getActiveConsumerCount()); } assertNull(template.receiveAndConvert(queue1.getName())); assertNull(template.receiveAndConvert(queue2.getName())); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testListenFromAnonQueue() throws Exception { AnonymousQueue queue = new AnonymousQueue(); CountDownLatch latch = new CountDownLatch(10); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer( template.getConnectionFactory()); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueueNames(queue.getName()); container.setConcurrentConsumers(2); GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("foo", queue); context.refresh();//ww w. ja v a2 s . com container.setApplicationContext(context); RabbitAdmin admin = new RabbitAdmin(this.template.getConnectionFactory()); admin.setApplicationContext(context); container.setRabbitAdmin(admin); container.afterPropertiesSet(); container.start(); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch.await(10, TimeUnit.SECONDS)); container.stop(); container.start(); latch = new CountDownLatch(10); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch.await(10, TimeUnit.SECONDS)); container.stop(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testExclusive() throws Exception { Log logger = spy(TestUtils.getPropertyValue(this.template.getConnectionFactory(), "logger", Log.class)); doReturn(true).when(logger).isInfoEnabled(); new DirectFieldAccessor(this.template.getConnectionFactory()).setPropertyValue("logger", logger); CountDownLatch latch1 = new CountDownLatch(1000); SimpleMessageListenerContainer container1 = new SimpleMessageListenerContainer( template.getConnectionFactory()); container1.setMessageListener(new MessageListenerAdapter(new PojoListener(latch1))); container1.setQueueNames(queue.getName()); GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton("foo", queue); context.refresh();/*from ww w . ja v a2s. com*/ container1.setApplicationContext(context); container1.setExclusive(true); container1.afterPropertiesSet(); container1.start(); int n = 0; while (n++ < 100 && container1.getActiveConsumerCount() < 1) { Thread.sleep(100); } assertTrue(n < 100); CountDownLatch latch2 = new CountDownLatch(1000); SimpleMessageListenerContainer container2 = new SimpleMessageListenerContainer( template.getConnectionFactory()); container2.setMessageListener(new MessageListenerAdapter(new PojoListener(latch2))); container2.setQueueNames(queue.getName()); container2.setApplicationContext(context); container2.setRecoveryInterval(1000); container2.setExclusive(true); // not really necessary, but likely people will make all consumers exclusive. ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); container2.setApplicationEventPublisher(publisher); container2.afterPropertiesSet(); Log containerLogger = spy(TestUtils.getPropertyValue(container2, "logger", Log.class)); doReturn(true).when(containerLogger).isWarnEnabled(); new DirectFieldAccessor(container2).setPropertyValue("logger", containerLogger); container2.start(); for (int i = 0; i < 1000; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertEquals(1000, latch2.getCount()); container1.stop(); // container 2 should recover and process the next batch of messages for (int i = 0; i < 1000; i++) { template.convertAndSend(queue.getName(), i + "foo"); } assertTrue(latch2.await(10, TimeUnit.SECONDS)); container2.stop(); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(logger, atLeastOnce()).info(captor.capture()); assertThat(captor.getAllValues(), contains(containsString("exclusive"))); ArgumentCaptor<ListenerContainerConsumerFailedEvent> eventCaptor = ArgumentCaptor .forClass(ListenerContainerConsumerFailedEvent.class); verify(publisher).publishEvent(eventCaptor.capture()); ListenerContainerConsumerFailedEvent event = eventCaptor.getValue(); assertEquals("Consumer raised exception, attempting restart", event.getReason()); assertFalse(event.isFatal()); assertThat(event.getThrowable(), instanceOf(AmqpIOException.class)); verify(containerLogger).warn(any()); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testRestartConsumerOnBasicQosIoException() throws Exception { this.template.convertAndSend(queue.getName(), "foo"); ConnectionFactory connectionFactory = new SingleConnectionFactory("localhost", BrokerTestUtils.getPort()); final AtomicBoolean networkGlitch = new AtomicBoolean(); class MockChannel extends PublisherCallbackChannelImpl { MockChannel(Channel delegate) { super(delegate); }/* www . j av a2s .com*/ @Override public void basicQos(int prefetchCount) throws IOException { if (networkGlitch.compareAndSet(false, true)) { throw new IOException("Intentional connection reset"); } super.basicQos(prefetchCount); } } Connection connection = spy(connectionFactory.createConnection()); when(connection.createChannel(anyBoolean())) .then(invocation -> new MockChannel((Channel) invocation.callRealMethod())); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); dfa.setPropertyValue("connection", connection); CountDownLatch latch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueueNames(queue.getName()); container.setRecoveryInterval(500); container.afterPropertiesSet(); container.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(networkGlitch.get()); container.stop(); ((DisposableBean) connectionFactory).destroy(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testRestartConsumerOnConnectionLossDuringQueueDeclare() throws Exception { this.template.convertAndSend(queue.getName(), "foo"); ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", BrokerTestUtils.getPort()); final AtomicBoolean networkGlitch = new AtomicBoolean(); class MockChannel extends PublisherCallbackChannelImpl { MockChannel(Channel delegate) { super(delegate); }//www. j a va 2s . c om @Override public DeclareOk queueDeclarePassive(String queue) throws IOException { if (networkGlitch.compareAndSet(false, true)) { getConnection().close(); throw new IOException("Intentional connection reset"); } return super.queueDeclarePassive(queue); } } Connection connection = spy(connectionFactory.createConnection()); when(connection.createChannel(anyBoolean())) .then(invocation -> new MockChannel((Channel) invocation.callRealMethod())); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); dfa.setPropertyValue("connection", connection); CountDownLatch latch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueueNames(queue.getName()); container.setRecoveryInterval(500); container.afterPropertiesSet(); container.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(networkGlitch.get()); container.stop(); ((DisposableBean) connectionFactory).destroy(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testRestartConsumerMissingQueue() throws Exception { Queue queue = new AnonymousQueue(); this.template.convertAndSend(queue.getName(), "foo"); ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", BrokerTestUtils.getPort()); CountDownLatch latch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueues(queue);//from w w w . j av a 2 s . com container.setRecoveryInterval(500); container.setMissingQueuesFatal(false); container.setDeclarationRetries(1); container.setFailedDeclarationRetryInterval(100); container.setRetryDeclarationInterval(30000); container.afterPropertiesSet(); container.start(); new RabbitAdmin(connectionFactory).declareQueue(queue); this.template.convertAndSend(queue.getName(), "foo"); assertTrue(latch.await(10, TimeUnit.SECONDS)); // verify properties propagated to consumer BlockingQueueConsumer consumer = (BlockingQueueConsumer) TestUtils .getPropertyValue(container, "consumers", Map.class).keySet().iterator().next(); assertEquals(1, TestUtils.getPropertyValue(consumer, "declarationRetries")); assertEquals(100L, TestUtils.getPropertyValue(consumer, "failedDeclarationRetryInterval")); assertEquals(30000L, TestUtils.getPropertyValue(consumer, "retryDeclarationInterval")); container.stop(); ((DisposableBean) connectionFactory).destroy(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
private SimpleMessageListenerContainer createContainer(Object listener, String... queueNames) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer( template.getConnectionFactory()); if (listener != null) { container.setMessageListener(listener); }/*w ww. j av a 2 s . c o m*/ container.setQueueNames(queueNames); container.afterPropertiesSet(); container.start(); return container; }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerLongTests.java
private void testChangeConsumerCountGuts(boolean transacted) throws Exception { final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost"); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory); try {/* ww w.ja v a2s.c om*/ container.setMessageListener(new MessageListenerAdapter(this)); container.setQueueNames("foo"); container.setAutoStartup(false); container.setConcurrentConsumers(2); container.setChannelTransacted(transacted); container.afterPropertiesSet(); assertEquals(2, ReflectionTestUtils.getField(container, "concurrentConsumers")); container.start(); waitForNConsumers(container, 2); container.setConcurrentConsumers(1); waitForNConsumers(container, 1); container.setMaxConcurrentConsumers(3); RabbitTemplate template = new RabbitTemplate(singleConnectionFactory); for (int i = 0; i < 20; i++) { template.convertAndSend("foo", "foo"); } waitForNConsumers(container, 2); // increased consumers due to work waitForNConsumers(container, 1, 20000); // should stop the extra consumer after 10 seconds idle container.setConcurrentConsumers(3); waitForNConsumers(container, 3); container.stop(); waitForNConsumers(container, 0); singleConnectionFactory.destroy(); } finally { container.stop(); } }