List of usage examples for org.springframework.amqp.rabbit.core RabbitTemplate receive
@Override @Nullable public Message receive(long timeoutMillis) throws AmqpException
From source file:org.springframework.amqp.rabbit.admin.RabbitTemplateConsumerExample.java
private static void receiveSync(RabbitTemplate template, int numMessages) { // receive response for (int i = 0; i < numMessages; i++) { Message message = template.receive(TestConstants.QUEUE_NAME); if (message == null) { System.out.println("Thread [" + Thread.currentThread().getId() + "] Received Null Message!"); } else {// w ww . j a va 2 s .co m System.out.println("Thread [" + Thread.currentThread().getId() + "] Received Message = " + new String(message.getBody())); Map<String, Object> headers = message.getMessageProperties().getHeaders(); Object objFloat = headers.get("float"); Object objcp = headers.get("object"); System.out.println("float header type = " + objFloat.getClass()); System.out.println("object header type = " + objcp.getClass()); } } }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java
@Test public void testAtomicSendAndReceiveWithRoutingKey() throws Exception { final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory()); ExecutorService executor = Executors.newFixedThreadPool(1); // Set up a consumer to respond to our producer Future<Message> received = executor.submit(new Callable<Message>() { public Message call() throws Exception { Message message = null;/* w w w . j a v a 2 s . c o m*/ for (int i = 0; i < 10; i++) { message = template.receive(ROUTE); if (message != null) { break; } Thread.sleep(100L); } assertNotNull("No message received", message); template.send(message.getMessageProperties().getReplyTo(), message); return message; } }); Message message = new Message("test-message".getBytes(), new MessageProperties()); Message reply = template.sendAndReceive(ROUTE, message); assertEquals(new String(message.getBody()), new String(received.get(1000, TimeUnit.MILLISECONDS).getBody())); assertNotNull("Reply is expected", reply); assertEquals(new String(message.getBody()), new String(reply.getBody())); // Message was consumed so nothing left on queue reply = template.receive(ROUTE); assertEquals(null, reply); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java
@Test public void testAtomicSendAndReceiveWithExchangeAndRoutingKey() throws Exception { final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory()); ExecutorService executor = Executors.newFixedThreadPool(1); // Set up a consumer to respond to our producer Future<Message> received = executor.submit(new Callable<Message>() { public Message call() throws Exception { Message message = null;/*from ww w.j a va 2 s . com*/ for (int i = 0; i < 10; i++) { message = template.receive(ROUTE); if (message != null) { break; } Thread.sleep(100L); } assertNotNull("No message received", message); template.send(message.getMessageProperties().getReplyTo(), message); return message; } }); Message message = new Message("test-message".getBytes(), new MessageProperties()); Message reply = template.sendAndReceive("", ROUTE, message); assertEquals(new String(message.getBody()), new String(received.get(1000, TimeUnit.MILLISECONDS).getBody())); assertNotNull("Reply is expected", reply); assertEquals(new String(message.getBody()), new String(reply.getBody())); // Message was consumed so nothing left on queue reply = template.receive(ROUTE); assertEquals(null, reply); }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java
@Test public void testAutoBindDLQPartionedConsumerFirst() throws Exception { RabbitTestBinder binder = getBinder(); ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties(); properties.getExtension().setPrefix("bindertest."); properties.getExtension().setAutoBindDlq(true); properties.setMaxAttempts(1); // disable retry properties.setPartitioned(true);//from w w w. j a v a2s . c o m properties.setInstanceIndex(0); DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties)); input0.setBeanName("test.input0DLQ"); Binding<MessageChannel> input0Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input0, properties); Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partDLQ.0", "default", new QueueChannel(), properties); properties.setInstanceIndex(1); DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties)); input1.setBeanName("test.input1DLQ"); Binding<MessageChannel> input1Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input1, properties); Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partDLQ.0", "default", new QueueChannel(), properties); ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties(); producerProperties.getExtension().setPrefix("bindertest."); producerProperties.getExtension().setAutoBindDlq(true); producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class); producerProperties.setPartitionSelectorClass(PartitionTestSupport.class); producerProperties.setPartitionCount(2); BindingProperties bindingProperties = createProducerBindingProperties(producerProperties); DirectChannel output = createBindableChannel("output", bindingProperties); output.setBeanName("test.output"); Binding<MessageChannel> outputBinding = binder.bindProducer("partDLQ.0", output, producerProperties); final CountDownLatch latch0 = new CountDownLatch(1); input0.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { if (latch0.getCount() <= 0) { throw new RuntimeException("dlq"); } latch0.countDown(); } }); final CountDownLatch latch1 = new CountDownLatch(1); input1.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { if (latch1.getCount() <= 0) { throw new RuntimeException("dlq"); } latch1.countDown(); } }); output.send(new GenericMessage<>(1)); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); output.send(new GenericMessage<>(0)); assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue(); output.send(new GenericMessage<>(1)); RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); template.setReceiveTimeout(10000); String streamDLQName = "bindertest.partDLQ.0.dlqPartGrp.dlq"; org.springframework.amqp.core.Message received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-1"); assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); output.send(new GenericMessage<>(0)); received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-0"); assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); input0Binding.unbind(); input1Binding.unbind(); defaultConsumerBinding1.unbind(); defaultConsumerBinding2.unbind(); outputBinding.unbind(); }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java
private void testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(final boolean withRetry) throws Exception { RabbitTestBinder binder = getBinder(); ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties(); properties.getExtension().setPrefix("bindertest."); properties.getExtension().setAutoBindDlq(true); properties.getExtension().setRepublishToDlq(true); properties.getExtension().setRepublishDeliveyMode(MessageDeliveryMode.NON_PERSISTENT); properties.setMaxAttempts(withRetry ? 2 : 1); properties.setPartitioned(true);/*w w w . j a v a 2 s.co m*/ properties.setInstanceIndex(0); DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties)); input0.setBeanName("test.input0DLQ"); Binding<MessageChannel> input0Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input0, properties); Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partPubDLQ.0", "default", new QueueChannel(), properties); properties.setInstanceIndex(1); DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties)); input1.setBeanName("test.input1DLQ"); Binding<MessageChannel> input1Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input1, properties); Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partPubDLQ.0", "default", new QueueChannel(), properties); ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties(); producerProperties.getExtension().setPrefix("bindertest."); producerProperties.getExtension().setAutoBindDlq(true); producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class); producerProperties.setPartitionSelectorClass(PartitionTestSupport.class); producerProperties.setPartitionCount(2); BindingProperties bindingProperties = createProducerBindingProperties(producerProperties); DirectChannel output = createBindableChannel("output", bindingProperties); output.setBeanName("test.output"); Binding<MessageChannel> outputBinding = binder.bindProducer("partPubDLQ.0", output, producerProperties); final CountDownLatch latch0 = new CountDownLatch(1); input0.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { if (latch0.getCount() <= 0) { throw new RuntimeException("dlq"); } latch0.countDown(); } }); final CountDownLatch latch1 = new CountDownLatch(1); input1.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { if (latch1.getCount() <= 0) { throw new RuntimeException("dlq"); } latch1.countDown(); } }); ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), "applicationContext", ApplicationContext.class); SubscribableChannel boundErrorChannel = context.getBean("bindertest.partPubDLQ.0.dlqPartGrp-0.errors", SubscribableChannel.class); SubscribableChannel globalErrorChannel = context.getBean("errorChannel", SubscribableChannel.class); final AtomicReference<Message<?>> boundErrorChannelMessage = new AtomicReference<>(); final AtomicReference<Message<?>> globalErrorChannelMessage = new AtomicReference<>(); final AtomicBoolean hasRecovererInCallStack = new AtomicBoolean(!withRetry); boundErrorChannel.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { boundErrorChannelMessage.set(message); String stackTrace = Arrays.toString(new RuntimeException().getStackTrace()); hasRecovererInCallStack.set(stackTrace.contains("ErrorMessageSendingRecoverer")); } }); globalErrorChannel.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { globalErrorChannelMessage.set(message); } }); output.send(new GenericMessage<>(1)); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); output.send(new GenericMessage<>(0)); assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue(); output.send(new GenericMessage<>(1)); RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); template.setReceiveTimeout(10000); String streamDLQName = "bindertest.partPubDLQ.0.dlqPartGrp.dlq"; org.springframework.amqp.core.Message received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey")) .isEqualTo("partPubDLQ.0-1"); assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); assertThat(received.getMessageProperties().getReceivedDeliveryMode()) .isEqualTo(MessageDeliveryMode.NON_PERSISTENT); output.send(new GenericMessage<>(0)); received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey")) .isEqualTo("partPubDLQ.0-0"); assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); // verify we got a message on the dedicated error channel and the global (via bridge) assertThat(boundErrorChannelMessage.get()).isNotNull(); assertThat(globalErrorChannelMessage.get()).isNotNull(); assertThat(hasRecovererInCallStack.get()).isEqualTo(withRetry); input0Binding.unbind(); input1Binding.unbind(); defaultConsumerBinding1.unbind(); defaultConsumerBinding2.unbind(); outputBinding.unbind(); }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java
@Test public void testAutoBindDLQPartitionedProducerFirst() throws Exception { RabbitTestBinder binder = getBinder(); ExtendedProducerProperties<RabbitProducerProperties> properties = createProducerProperties(); properties.getExtension().setPrefix("bindertest."); properties.getExtension().setAutoBindDlq(true); properties.setRequiredGroups("dlqPartGrp"); properties.setPartitionKeyExtractorClass(PartitionTestSupport.class); properties.setPartitionSelectorClass(PartitionTestSupport.class); properties.setPartitionCount(2);//from w w w . j av a 2 s . com DirectChannel output = createBindableChannel("output", createProducerBindingProperties(properties)); output.setBeanName("test.output"); Binding<MessageChannel> outputBinding = binder.bindProducer("partDLQ.1", output, properties); ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties(); consumerProperties.getExtension().setPrefix("bindertest."); consumerProperties.getExtension().setAutoBindDlq(true); consumerProperties.setMaxAttempts(1); // disable retry consumerProperties.setPartitioned(true); consumerProperties.setInstanceIndex(0); DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(consumerProperties)); input0.setBeanName("test.input0DLQ"); Binding<MessageChannel> input0Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input0, consumerProperties); Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partDLQ.1", "defaultConsumer", new QueueChannel(), consumerProperties); consumerProperties.setInstanceIndex(1); DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(consumerProperties)); input1.setBeanName("test.input1DLQ"); Binding<MessageChannel> input1Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input1, consumerProperties); Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partDLQ.1", "defaultConsumer", new QueueChannel(), consumerProperties); final CountDownLatch latch0 = new CountDownLatch(1); input0.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { if (latch0.getCount() <= 0) { throw new RuntimeException("dlq"); } latch0.countDown(); } }); final CountDownLatch latch1 = new CountDownLatch(1); input1.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { if (latch1.getCount() <= 0) { throw new RuntimeException("dlq"); } latch1.countDown(); } }); output.send(new GenericMessage<Integer>(1)); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); output.send(new GenericMessage<Integer>(0)); assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue(); output.send(new GenericMessage<Integer>(1)); RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); template.setReceiveTimeout(10000); String streamDLQName = "bindertest.partDLQ.1.dlqPartGrp.dlq"; org.springframework.amqp.core.Message received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-1"); assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); assertThat(received.getMessageProperties().getReceivedDeliveryMode()) .isEqualTo(MessageDeliveryMode.PERSISTENT); output.send(new GenericMessage<Integer>(0)); received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-0"); assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); input0Binding.unbind(); input1Binding.unbind(); defaultConsumerBinding1.unbind(); defaultConsumerBinding2.unbind(); outputBinding.unbind(); }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java
@Test public void testAutoBindDLQwithRepublish() throws Exception { // pre-declare the queue with dead-lettering, users can also use a policy RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource()); Map<String, Object> args = new HashMap<String, Object>(); args.put("x-dead-letter-exchange", TEST_PREFIX + "DLX"); args.put("x-dead-letter-routing-key", TEST_PREFIX + "dlqpubtest.default"); Queue queue = new Queue(TEST_PREFIX + "dlqpubtest.default", true, false, false, args); admin.declareQueue(queue);/*from www . j a v a 2 s .c o m*/ RabbitTestBinder binder = getBinder(); ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties(); consumerProperties.getExtension().setPrefix(TEST_PREFIX); consumerProperties.getExtension().setAutoBindDlq(true); consumerProperties.getExtension().setRepublishToDlq(true); consumerProperties.setMaxAttempts(1); // disable retry consumerProperties.getExtension().setDurableSubscription(true); DirectChannel moduleInputChannel = createBindableChannel("input", createConsumerBindingProperties(consumerProperties)); moduleInputChannel.setBeanName("dlqPubTest"); moduleInputChannel.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { throw new RuntimeException("foo"); } }); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.dlqpubtest", "foo", moduleInputChannel, consumerProperties); RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest.foo", "foo"); int n = 0; while (n++ < 100) { org.springframework.amqp.core.Message deadLetter = template .receive(TEST_PREFIX + "foo.dlqpubtest.foo.dlq"); if (deadLetter != null) { assertThat(new String(deadLetter.getBody())).isEqualTo("foo"); assertThat(deadLetter.getMessageProperties().getHeaders()).containsKey(("x-exception-stacktrace")); break; } Thread.sleep(100); } assertThat(n).isLessThan(100); consumerBinding.unbind(); }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java
@Test public void testAutoBindDLQwithRepublish() throws Exception { // pre-declare the queue with dead-lettering, users can also use a policy RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource()); Map<String, Object> args = new HashMap<String, Object>(); args.put("x-dead-letter-exchange", "xdbustest.DLX"); Queue queue = new Queue("xdbustest.dlqpubtest", true, false, false, args); admin.declareQueue(queue);//from w w w . j av a 2s . c om MessageBus bus = getMessageBus(); Properties properties = new Properties(); properties.put("prefix", "xdbustest."); properties.put("autoBindDLQ", "true"); properties.put("republishToDLQ", "true"); properties.put("maxAttempts", "1"); // disable retry properties.put("requeue", "false"); DirectChannel moduleInputChannel = new DirectChannel(); moduleInputChannel.setBeanName("dlqPubTest"); moduleInputChannel.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { throw new RuntimeException("foo"); } }); bus.bindConsumer("dlqpubtest", moduleInputChannel, properties); RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); template.convertAndSend("", "xdbustest.dlqpubtest", "foo"); int n = 0; while (n++ < 100) { org.springframework.amqp.core.Message deadLetter = template.receive("xdbustest.dlqpubtest.dlq"); if (deadLetter != null) { assertEquals("foo", new String(deadLetter.getBody())); assertNotNull(deadLetter.getMessageProperties().getHeaders().get("x-exception-stacktrace")); break; } Thread.sleep(100); } assertTrue(n < 100); bus.unbindConsumer("dlqpubtest", moduleInputChannel); admin.deleteQueue("xdbustest.dlqpubtest.dlq"); admin.deleteQueue("xdbustest.dlqpubtest"); admin.deleteExchange("xdbustest.DLX"); }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java
@SuppressWarnings("unchecked") @Test/*from w w w . j a v a2 s.co m*/ public void testBatchingAndCompression() throws Exception { RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); MessageBus bus = getMessageBus(); Properties properties = new Properties(); properties.put("deliveryMode", "NON_PERSISTENT"); properties.put("batchingEnabled", "true"); properties.put("batchSize", "2"); properties.put("batchBufferLimit", "100000"); properties.put("batchTimeout", "30000"); properties.put("compress", "true"); DirectChannel output = new DirectChannel(); output.setBeanName("batchingProducer"); bus.bindProducer("batching.0", output, properties); while (template.receive("xdbus.batching.0") != null) { } Log logger = spy(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.logger", Log.class)); new DirectFieldAccessor(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor")) .setPropertyValue("logger", logger); when(logger.isTraceEnabled()).thenReturn(true); assertEquals(Deflater.BEST_SPEED, TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.level")); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Object out = spyOn("batching.0").receive(false); assertThat(out, instanceOf(byte[].class)); assertEquals("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar", new String((byte[]) out)); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(logger).trace(captor.capture()); assertThat(captor.getValue().toString(), containsString("Compressed 14 to ")); QueueChannel input = new QueueChannel(); input.setBeanName("batchingConsumer"); bus.bindConsumer("batching.0", input, null); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Message<byte[]> in = (Message<byte[]>) input.receive(10000); assertNotNull(in); assertEquals("foo", new String(in.getPayload())); in = (Message<byte[]>) input.receive(10000); assertNotNull(in); assertEquals("bar", new String(in.getPayload())); assertNull(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)); bus.unbindProducers("batching.0"); bus.unbindConsumers("batching.0"); }