List of usage examples for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer afterPropertiesSet
@Override public final void afterPropertiesSet()
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
@Test public void testChangeQueues() throws Exception { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); Connection connection = mock(Connection.class); Channel channel1 = mock(Channel.class); Channel channel2 = mock(Channel.class); when(channel1.isOpen()).thenReturn(true); when(channel2.isOpen()).thenReturn(true); when(connectionFactory.createConnection()).thenReturn(connection); when(connection.createChannel(false)).thenReturn(channel1, channel2); List<Consumer> consumers = new ArrayList<Consumer>(); AtomicInteger consumerTag = new AtomicInteger(); CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(2); setupMockConsume(channel1, consumers, consumerTag, latch1); setUpMockCancel(channel1, consumers); setupMockConsume(channel2, consumers, consumerTag, latch2); setUpMockCancel(channel2, consumers); final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setQueueNames("foo"); container.setReceiveTimeout(1);//from w w w. jav a 2 s . c o m container.setMessageListener((MessageListener) message -> { }); container.afterPropertiesSet(); container.start(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); container.addQueueNames("bar"); assertTrue(latch2.await(10, TimeUnit.SECONDS)); container.stop(); verify(channel1).basicCancel("0"); verify(channel2, atLeastOnce()).basicCancel("1"); verify(channel2, atLeastOnce()).basicCancel("2"); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
@SuppressWarnings("unchecked") @Test//from ww w . ja v a2 s . c o m public void testAddQueuesAndStartInCycle() throws Exception { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); Connection connection = mock(Connection.class); Channel channel1 = mock(Channel.class); when(channel1.isOpen()).thenReturn(true); when(connectionFactory.createConnection()).thenReturn(connection); when(connection.createChannel(false)).thenReturn(channel1); final AtomicInteger count = new AtomicInteger(); doAnswer(invocation -> { Consumer cons = (Consumer) invocation.getArguments()[6]; String consumerTag = "consFoo" + count.incrementAndGet(); cons.handleConsumeOk(consumerTag); return consumerTag; }).when(channel1).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener((MessageListener) message -> { }); container.afterPropertiesSet(); for (int i = 0; i < 10; i++) { container.addQueueNames("foo" + i); if (!container.isRunning()) { container.start(); } } container.stop(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
@SuppressWarnings("unchecked") @Test//from www . j a va 2s.com public void testWithConnectionPerListenerThread() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock( com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class); com.rabbitmq.client.Connection mockConnection2 = mock(com.rabbitmq.client.Connection.class); Channel mockChannel1 = mock(Channel.class); Channel mockChannel2 = mock(Channel.class); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())) .thenReturn(mockConnection1).thenReturn(mockConnection2).thenReturn(null); when(mockConnection1.createChannel()).thenReturn(mockChannel1).thenReturn(null); when(mockConnection2.createChannel()).thenReturn(mockChannel2).thenReturn(null); when(mockChannel1.isOpen()).thenReturn(true); when(mockConnection1.isOpen()).thenReturn(true); when(mockChannel2.isOpen()).thenReturn(true); when(mockConnection2.isOpen()).thenReturn(true); CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory); ccf.setCacheMode(CacheMode.CONNECTION); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf); container.setConcurrentConsumers(2); container.setQueueNames("foo"); container.afterPropertiesSet(); CountDownLatch latch1 = new CountDownLatch(2); CountDownLatch latch2 = new CountDownLatch(2); doAnswer(messageToConsumer(mockChannel1, container, false, latch1)).when(mockChannel1).basicConsume( anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); doAnswer(messageToConsumer(mockChannel2, container, false, latch1)).when(mockChannel2).basicConsume( anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); doAnswer(messageToConsumer(mockChannel1, container, true, latch2)).when(mockChannel1) .basicCancel(anyString()); doAnswer(messageToConsumer(mockChannel2, container, true, latch2)).when(mockChannel2) .basicCancel(anyString()); container.start(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); Set<?> consumers = TestUtils.getPropertyValue(container, "consumers", Map.class).keySet(); container.stop(); assertTrue(latch2.await(10, TimeUnit.SECONDS)); waitForConsumersToStop(consumers); Set<?> allocatedConnections = TestUtils.getPropertyValue(ccf, "allocatedConnections", Set.class); assertEquals(2, allocatedConnections.size()); assertEquals("1", ccf.getCacheProperties().get("openConnections")); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
@SuppressWarnings("unchecked") @Test/*from w w w .j av a 2 s . com*/ public void testConsumerCancel() throws Exception { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); Connection connection = mock(Connection.class); Channel channel = mock(Channel.class); when(connectionFactory.createConnection()).thenReturn(connection); when(connection.createChannel(false)).thenReturn(channel); final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>(); doAnswer(invocation -> { consumer.set((Consumer) invocation.getArguments()[6]); consumer.get().handleConsumeOk("foo"); return "foo"; }).when(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setQueueNames("foo"); container.setMessageListener((MessageListener) message -> { }); container.setReceiveTimeout(1); container.afterPropertiesSet(); container.start(); verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class)); Log logger = spy(TestUtils.getPropertyValue(container, "logger", Log.class)); doReturn(false).when(logger).isDebugEnabled(); final CountDownLatch latch = new CountDownLatch(1); doAnswer(invocation -> { if (((String) invocation.getArguments()[0]).startsWith("Consumer raised exception")) { latch.countDown(); } return invocation.callRealMethod(); }).when(logger).warn(any()); new DirectFieldAccessor(container).setPropertyValue("logger", logger); consumer.get().handleCancel("foo"); assertTrue(latch.await(10, TimeUnit.SECONDS)); container.stop(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
@Test public void testContainerNotRecoveredAfterExhaustingRecoveryBackOff() throws Exception { SimpleMessageListenerContainer container = spy( new SimpleMessageListenerContainer(mock(ConnectionFactory.class))); container.setQueueNames("foo"); container.setRecoveryBackOff(new FixedBackOff(100, 3)); container.setConcurrentConsumers(3); doAnswer(invocation -> {/*www.j a v a 2 s. c o m*/ BlockingQueueConsumer consumer = spy((BlockingQueueConsumer) invocation.callRealMethod()); doThrow(RuntimeException.class).when(consumer).start(); return consumer; }).when(container).createBlockingQueueConsumer(); container.afterPropertiesSet(); container.start(); // Since backOff exhausting makes listenerContainer as invalid (calls stop()), // it is enough to check the listenerContainer activity int n = 0; while (container.isActive() && n++ < 100) { Thread.sleep(100); } assertThat(n, lessThanOrEqualTo(100)); }
From source file:org.springframework.cloud.stream.binder.rabbit.LocalizedQueueConnectionFactoryTests.java
@SuppressWarnings("unchecked") @Test/* ww w . java2 s. c om*/ public void testFailOver() throws Exception { ConnectionFactory defaultConnectionFactory = mockCF("localhost:1234"); String rabbit1 = "localhost:1235"; String rabbit2 = "localhost:1236"; String[] addresses = new String[] { rabbit1, rabbit2 }; String[] adminAddresses = 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); LocalizedQueueConnectionFactory lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory, addresses, adminAddresses, nodes, vhost, username, password, false, null) { private final String[] nodes = new String[] { "rabbit@foo", "rabbit@bar" }; @Override protected RestTemplate createRestTemplate(String adminUri) { return doCreateRestTemplate(adminUri, firstServer.get() ? nodes[0] : nodes[1]); } @Override protected ConnectionFactory createConnectionFactory(String address) throws Exception { return mockCF(address); } }; Log logger = spy(TestUtils.getPropertyValue(lqcf, "logger", Log.class)); new DirectFieldAccessor(lqcf).setPropertyValue("logger", logger); when(logger.isDebugEnabled()).thenReturn(true); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(lqcf); container.setQueueNames("q"); container.afterPropertiesSet(); container.start(); Channel channel = this.channels.get(rabbit1); verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), Matchers.any(Consumer.class)); verify(logger, atLeast(1)).debug(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); when(channel.isOpen()).thenReturn(false); when(this.connections.get(rabbit1).isOpen()).thenReturn(false); this.consumers.get(rabbit1).handleCancel(consumerTags.get(rabbit1)); assertTrue(latch.await(10, TimeUnit.SECONDS)); channel = this.channels.get(rabbit2); verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), Matchers.any(Consumer.class)); container.stop(); verify(logger, atLeast(1)).debug(captor.capture()); assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@bar at: localhost:1236")); }
From source file:org.springframework.integration.amqp.outbound.AsyncAmqpGatewayTests.java
@Test public void testConfirmsAndReturns() throws Exception { CachingConnectionFactory ccf = new CachingConnectionFactory("localhost"); ccf.setPublisherConfirms(true);/*from w w w .j a v a 2s .c om*/ ccf.setPublisherReturns(true); RabbitTemplate template = new RabbitTemplate(ccf); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf); container.setBeanName("replyContainer"); container.setQueueNames("asyncRQ1"); container.afterPropertiesSet(); container.start(); AsyncRabbitTemplate asyncTemplate = new AsyncRabbitTemplate(template, container); asyncTemplate.setEnableConfirms(true); asyncTemplate.setMandatory(true); SimpleMessageListenerContainer receiver = new SimpleMessageListenerContainer(ccf); receiver.setBeanName("receiver"); receiver.setQueueNames("asyncQ1"); final CountDownLatch waitForAckBeforeReplying = new CountDownLatch(1); MessageListenerAdapter messageListener = new MessageListenerAdapter( (ReplyingMessageListener<String, String>) foo -> { try { waitForAckBeforeReplying.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return foo.toUpperCase(); }); receiver.setMessageListener(messageListener); receiver.afterPropertiesSet(); receiver.start(); AsyncAmqpOutboundGateway gateway = new AsyncAmqpOutboundGateway(asyncTemplate); Log logger = spy(TestUtils.getPropertyValue(gateway, "logger", Log.class)); given(logger.isDebugEnabled()).willReturn(true); final CountDownLatch replyTimeoutLatch = new CountDownLatch(1); willAnswer(invocation -> { invocation.callRealMethod(); replyTimeoutLatch.countDown(); return null; }).given(logger).debug(startsWith("Reply not required and async timeout for")); new DirectFieldAccessor(gateway).setPropertyValue("logger", logger); QueueChannel outputChannel = new QueueChannel(); outputChannel.setBeanName("output"); QueueChannel returnChannel = new QueueChannel(); returnChannel.setBeanName("returns"); QueueChannel ackChannel = new QueueChannel(); ackChannel.setBeanName("acks"); QueueChannel errorChannel = new QueueChannel(); errorChannel.setBeanName("errors"); gateway.setOutputChannel(outputChannel); gateway.setReturnChannel(returnChannel); gateway.setConfirmAckChannel(ackChannel); gateway.setConfirmNackChannel(ackChannel); gateway.setConfirmCorrelationExpressionString("#this"); gateway.setExchangeName(""); gateway.setRoutingKey("asyncQ1"); gateway.setBeanFactory(mock(BeanFactory.class)); gateway.afterPropertiesSet(); gateway.start(); Message<?> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); Message<?> ack = ackChannel.receive(10000); assertNotNull(ack); assertEquals("foo", ack.getPayload()); assertEquals(true, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); waitForAckBeforeReplying.countDown(); Message<?> received = outputChannel.receive(10000); assertNotNull(received); assertEquals("FOO", received.getPayload()); // timeout tests asyncTemplate.setReceiveTimeout(10); receiver.setMessageListener(message1 -> { }); // reply timeout with no requiresReply message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); assertTrue(replyTimeoutLatch.await(10, TimeUnit.SECONDS)); // reply timeout with requiresReply gateway.setRequiresReply(true); message = MessageBuilder.withPayload("baz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); received = errorChannel.receive(10000); assertThat(received, instanceOf(ErrorMessage.class)); ErrorMessage error = (ErrorMessage) received; assertThat(error.getPayload(), instanceOf(MessagingException.class)); assertThat(error.getPayload().getCause(), instanceOf(AmqpReplyTimeoutException.class)); asyncTemplate.setReceiveTimeout(30000); receiver.setMessageListener(messageListener); // error on sending result DirectChannel errorForce = new DirectChannel(); errorForce.setBeanName("errorForce"); errorForce.subscribe(message1 -> { throw new RuntimeException("intentional"); }); gateway.setOutputChannel(errorForce); message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); received = errorChannel.receive(10000); assertThat(received, instanceOf(ErrorMessage.class)); error = (ErrorMessage) received; assertThat(error.getPayload(), instanceOf(MessagingException.class)); assertEquals("QUX", ((MessagingException) error.getPayload()).getFailedMessage().getPayload()); gateway.setRoutingKey(UUID.randomUUID().toString()); message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); Message<?> returned = returnChannel.receive(10000); assertNotNull(returned); assertEquals("fiz", returned.getPayload()); ackChannel.receive(10000); ackChannel.purge(null); asyncTemplate = mock(AsyncRabbitTemplate.class); RabbitMessageFuture future = asyncTemplate.new RabbitMessageFuture(null, null); willReturn(future).given(asyncTemplate).sendAndReceive(anyString(), anyString(), any(org.springframework.amqp.core.Message.class)); DirectFieldAccessor dfa = new DirectFieldAccessor(future); dfa.setPropertyValue("nackCause", "nacknack"); SettableListenableFuture<Boolean> confirmFuture = new SettableListenableFuture<Boolean>(); confirmFuture.set(false); dfa.setPropertyValue("confirm", confirmFuture); new DirectFieldAccessor(gateway).setPropertyValue("template", asyncTemplate); message = MessageBuilder.withPayload("buz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); ack = ackChannel.receive(10000); assertNotNull(ack); assertEquals("buz", ack.getPayload()); assertEquals("nacknack", ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_NACK_CAUSE)); assertEquals(false, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); asyncTemplate.stop(); receiver.stop(); ccf.destroy(); }
From source file:org.springframework.integration.x.rabbit.RabbitChannelRegistry.java
@Override public void createInbound(final String name, MessageChannel moduleInputChannel, final Collection<MediaType> acceptedMediaTypes, boolean aliasHint) { if (logger.isInfoEnabled()) { logger.info("declaring queue for inbound: " + name); }/* w w w . java 2s .co m*/ this.rabbitAdmin.declareQueue(new Queue(name)); SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer( this.connectionFactory); if (this.concurrentConsumers != null) { listenerContainer.setConcurrentConsumers(this.concurrentConsumers); } listenerContainer.setQueueNames(name); listenerContainer.afterPropertiesSet(); AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer); DirectChannel bridgeToModuleChannel = new DirectChannel(); bridgeToModuleChannel.setBeanName(name + ".bridge"); adapter.setOutputChannel(bridgeToModuleChannel); adapter.setHeaderMapper(this.mapper); adapter.setBeanName("inbound." + name); adapter.afterPropertiesSet(); this.lifecycleBeans.add(adapter); ReceivingHandler convertingBridge = new ReceivingHandler(acceptedMediaTypes); convertingBridge.setOutputChannel(moduleInputChannel); convertingBridge.setBeanName(name + ".convert.bridge"); convertingBridge.afterPropertiesSet(); bridgeToModuleChannel.subscribe(convertingBridge); adapter.start(); }
From source file:org.springframework.integration.x.rabbit.RabbitChannelRegistry.java
@Override public void tap(String tapModule, final String name, MessageChannel tapModuleInputChannel) { SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer( this.connectionFactory); if (this.concurrentConsumers != null) { listenerContainer.setConcurrentConsumers(this.concurrentConsumers); }/*from w w w .j av a 2 s .c o m*/ Queue queue = this.rabbitAdmin.declareQueue(); Binding binding = BindingBuilder.bind(queue).to(new FanoutExchange("tap." + name)); this.rabbitAdmin.declareBinding(binding); listenerContainer.setQueues(queue); listenerContainer.afterPropertiesSet(); AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer); DirectChannel bridgeToTapChannel = new DirectChannel(); bridgeToTapChannel.setBeanName(tapModule + ".bridge"); adapter.setOutputChannel(bridgeToTapChannel); adapter.setHeaderMapper(this.mapper); adapter.setBeanName("tap." + name); adapter.setComponentName(tapModule + "." + "tapAdapter"); adapter.afterPropertiesSet(); this.lifecycleBeans.add(adapter); // TODO: media types need to be passed in by Tap. Collection<MediaType> acceptedMediaTypes = Collections.singletonList(MediaType.ALL); ReceivingHandler convertingBridge = new ReceivingHandler(acceptedMediaTypes); convertingBridge.setOutputChannel(tapModuleInputChannel); convertingBridge.setBeanName(name + ".convert.bridge"); convertingBridge.afterPropertiesSet(); bridgeToTapChannel.subscribe(convertingBridge); adapter.start(); }
From source file:org.springframework.integration.x.rabbit.RabbitMessageBus.java
private void doRegisterConsumer(String name, MessageChannel moduleInputChannel, Queue queue) { SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer( this.connectionFactory); if (this.concurrentConsumers != null) { listenerContainer.setConcurrentConsumers(this.concurrentConsumers); }/*from w w w . j a v a 2 s . c o m*/ listenerContainer.setQueues(queue); Advice advice = new StatelessRetryOperationsInterceptorFactoryBean().getObject(); listenerContainer.setAdviceChain(new Advice[] { advice }); listenerContainer.afterPropertiesSet(); AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer); DirectChannel bridgeToModuleChannel = new DirectChannel(); bridgeToModuleChannel.setBeanName(name + ".bridge"); adapter.setOutputChannel(bridgeToModuleChannel); adapter.setHeaderMapper(this.mapper); adapter.setBeanName("inbound." + name); adapter.afterPropertiesSet(); addBinding(Binding.forConsumer(adapter, moduleInputChannel)); ReceivingHandler convertingBridge = new ReceivingHandler(); convertingBridge.setOutputChannel(moduleInputChannel); convertingBridge.setBeanName(name + ".convert.bridge"); convertingBridge.afterPropertiesSet(); bridgeToModuleChannel.subscribe(convertingBridge); adapter.start(); }