List of usage examples for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer afterPropertiesSet
@Override public final void afterPropertiesSet()
From source file:com.jbrisbin.groovy.mqdsl.RabbitMQBuilder.java
@Override public Object invokeMethod(String methodName, Object args) { if (CONSUME.equals(methodName)) { Consume consume = new Consume(); SimpleMessageListenerContainer listenerContainer = consume.getListenerContainer(); Object[] params = (Object[]) args; for (Object param : params) { if (param instanceof Map) { Map paramMap = (Map) param; if (paramMap.containsKey(ON_MESSAGE)) { Object onMessage = paramMap.get(ON_MESSAGE); if (onMessage instanceof String) { consume.setEventName((String) onMessage); } else if (onMessage instanceof Closure) { consume.setDelegate((Closure) onMessage); } else if (onMessage instanceof MessageListener) { listenerContainer.setMessageListener(onMessage); } else { listenerContainer.setMessageListener(new MessageListenerAdapter(onMessage)); }/*from w w w .ja va 2 s . co m*/ } if (paramMap.containsKey(ACK)) { AcknowledgeMode mode = AcknowledgeMode.valueOf(paramMap.get(ACK).toString().toUpperCase()); listenerContainer.setAcknowledgeMode(mode); } else { listenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO); } } else if (param instanceof Closure) { consume.setDelegate((Closure) param); } } listenerContainer.setQueues(currentQueue); listenerContainer.afterPropertiesSet(); listenerContainer.start(); listenerContainers.add(listenerContainer); return super.invokeMethod(methodName, consume); } else if (PUBLISH.equals(methodName)) { Publish publish = new Publish(); publish.invokeMethod(CALL, args); return super.invokeMethod(methodName, publish); } return super.invokeMethod(methodName, args); }
From source file:org.springframework.amqp.rabbit.connection.LocalizedQueueConnectionFactoryTests.java
@SuppressWarnings("unchecked") @Test// w w w. jav a2 s . com public void testFailOver() throws Exception { ConnectionFactory defaultConnectionFactory = mockCF("localhost:1234", null); String rabbit1 = "localhost:1235"; String rabbit2 = "localhost:1236"; String[] addresses = new String[] { rabbit1, rabbit2 }; String[] adminUris = new String[] { "http://localhost:11235", "http://localhost:11236" }; String[] nodes = new String[] { "rabbit@foo", "rabbit@bar" }; String vhost = "/"; String username = "guest"; String password = "guest"; final AtomicBoolean firstServer = new AtomicBoolean(true); final Client client1 = doCreateClient(adminUris[0], username, password, nodes[0]); final Client client2 = doCreateClient(adminUris[1], username, password, nodes[1]); final Map<String, ConnectionFactory> mockCFs = new HashMap<String, ConnectionFactory>(); CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(1); mockCFs.put(rabbit1, mockCF(rabbit1, latch1)); mockCFs.put(rabbit2, mockCF(rabbit2, latch2)); LocalizedQueueConnectionFactory lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory, addresses, adminUris, nodes, vhost, username, password, false, null) { @Override protected Client createClient(String adminUri, String username, String password) throws MalformedURLException, URISyntaxException { return firstServer.get() ? client1 : client2; } @Override protected ConnectionFactory createConnectionFactory(String address, String node) throws Exception { return mockCFs.get(address); } }; Log logger = spy(TestUtils.getPropertyValue(lqcf, "logger", Log.class)); doReturn(true).when(logger).isInfoEnabled(); new DirectFieldAccessor(lqcf).setPropertyValue("logger", logger); doAnswer(new CallsRealMethods()).when(logger).debug(anyString()); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(lqcf); container.setQueueNames("q"); container.afterPropertiesSet(); container.start(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); Channel channel = this.channels.get(rabbit1); assertNotNull(channel); verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), Matchers.any(Consumer.class)); verify(logger, atLeast(1)).info(captor.capture()); assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@foo at: localhost:1235")); // Fail rabbit1 and verify the container switches to rabbit2 firstServer.set(false); this.consumers.get(rabbit1).handleCancel(consumerTags.get(rabbit1)); assertTrue(latch2.await(10, TimeUnit.SECONDS)); channel = this.channels.get(rabbit2); assertNotNull(channel); verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), Matchers.any(Consumer.class)); container.stop(); verify(logger, atLeast(1)).info(captor.capture()); assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@bar at: localhost:1236")); }
From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java
@Test public void testDebatchByContainer() 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 w w .j a va 2 s . c o m container.setMessageListener((MessageListener) message -> { received.add(message); latch.countDown(); }); container.setReceiveTimeout(100); 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); 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.BatchingRabbitTemplateTests.java
@Test public void testDebatchByContainerPerformance() throws Exception { final List<Message> received = new ArrayList<Message>(); int count = 100000; final CountDownLatch latch = new CountDownLatch(count); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory); container.setQueueNames(ROUTE);/*from w w w . j a v a2 s .co m*/ container.setMessageListener((MessageListener) message -> { received.add(message); latch.countDown(); }); container.setReceiveTimeout(100); container.setPrefetchCount(1000); container.setTxSize(1000); container.afterPropertiesSet(); container.start(); try { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(1000, Integer.MAX_VALUE, 30000); BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler); // RabbitTemplate template = new RabbitTemplate(); template.setConnectionFactory(this.connectionFactory); MessageProperties props = new MessageProperties(); props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); Message message = new Message(new byte[256], props); StopWatch watch = new StopWatch(); watch.start(); for (int i = 0; i < count; i++) { template.send("", ROUTE, message); } assertTrue(latch.await(60, TimeUnit.SECONDS)); watch.stop(); // System .out .println(watch.getTotalTimeMillis()); assertEquals(count, received.size()); } finally { container.stop(); } }
From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java
@Test public void testDebatchByContainerBadMessageRejected() throws Exception { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory); container.setQueueNames(ROUTE);// www. j a va 2 s.c o m container.setMessageListener((MessageListener) message -> { }); container.setReceiveTimeout(100); ConditionalRejectingErrorHandler errorHandler = new ConditionalRejectingErrorHandler(); container.setErrorHandler(errorHandler); container.afterPropertiesSet(); container.start(); Log logger = spy(TestUtils.getPropertyValue(errorHandler, "logger", Log.class)); doReturn(true).when(logger).isWarnEnabled(); doAnswer(new DoesNothing()).when(logger).warn(anyString(), any(Throwable.class)); new DirectFieldAccessor(errorHandler).setPropertyValue("logger", logger); try { RabbitTemplate template = new RabbitTemplate(); template.setConnectionFactory(this.connectionFactory); MessageProperties props = new MessageProperties(); props.getHeaders().put(MessageProperties.SPRING_BATCH_FORMAT, MessageProperties.BATCH_FORMAT_LENGTH_HEADER4); Message message = new Message("\u0000\u0000\u0000\u0004foo".getBytes(), props); template.send("", ROUTE, message); Thread.sleep(1000); ArgumentCaptor<Object> arg1 = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<Throwable> arg2 = ArgumentCaptor.forClass(Throwable.class); verify(logger).warn(arg1.capture(), arg2.capture()); assertThat(arg2.getValue().getMessage(), containsString("Bad batched message received")); } finally { container.stop(); } }
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 w w . j a va 2s .co m*/ 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.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 www. j a v a2 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();//from w w w. j a v a 2 s . co m 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 www. j ava2s.co m*/ 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); }/*from ww w . j a v a 2 s. co m*/ @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(); }