Example usage for org.springframework.amqp.rabbit.core RabbitTemplate RabbitTemplate

List of usage examples for org.springframework.amqp.rabbit.core RabbitTemplate RabbitTemplate

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.core RabbitTemplate RabbitTemplate.

Prototype

public RabbitTemplate(ConnectionFactory connectionFactory) 

Source Link

Document

Create a rabbit template with default strategies and settings.

Usage

From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerWithRabbitMQ.java

public static void main(String[] args) throws InterruptedException {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
    connectionFactory.setHost("localhost");
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");
    assertNotNull(connectionFactory);//  ww w.  ja  v  a2s .co  m

    MessageConverter messageConverter = new SimpleMessageConverter();
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames("foo");
    container.setPrefetchCount(1000);
    container.setTxSize(500);
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    container.setConcurrentConsumers(20);
    container.setMessageListener(new MessageListenerAdapter(new SimpleAdapter(), messageConverter));
    container.start();

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(messageConverter);
    List<BlockingQueue<?>> queues = getQueues(container);

    Thread.sleep(10000);
    int n = 0;
    while (true) {
        for (int i = 1; i <= 200; i++) {

            template.send("foo", "",
                    new Message(
                            "foo # ID: id".replace("#", String.valueOf(i))
                                    .replace("id", java.util.UUID.randomUUID().toString()).getBytes(),
                            messageProperties));

        }
        Thread.sleep(1000);
        if (++n % 10 == 0) {
            logger.warn(count(queues));
        }
    }
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testProducerProperties() throws Exception {
    RabbitTestBinder binder = getBinder();
    Binding<MessageChannel> producerBinding = binder.bindProducer("props.0",
            createBindableChannel("input", new BindingProperties()), createProducerProperties());
    Lifecycle endpoint = extractEndpoint(producerBinding);
    MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode",
            MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.PERSISTENT);
    List<?> requestHeaders = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers",
            List.class);
    assertThat(requestHeaders).hasSize(2);
    producerBinding.unbind();/*  w ww. j av a  2  s  .c o m*/
    assertThat(endpoint.isRunning()).isFalse();
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isFalse();

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("foo.");
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setHeaderPatterns(new String[] { "foo" });
    producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("'foo'"));
    producerProperties.setPartitionKeyExtractorClass(TestPartitionKeyExtractorClass.class);
    producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("0"));
    producerProperties.setPartitionSelectorClass(TestPartitionSelectorClass.class);
    producerProperties.setPartitionCount(1);
    producerProperties.getExtension().setTransacted(true);
    producerProperties.getExtension().setDelayExpression("42");
    producerProperties.setRequiredGroups("prodPropsRequired");

    BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel channel = createBindableChannel("output", producerBindingProperties);
    producerBinding = binder.bindProducer("props.0", channel, producerProperties);
    endpoint = extractEndpoint(producerBinding);
    assertThat(getEndpointRouting(endpoint))
            .isEqualTo("'props.0-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
    assertThat(
            TestUtils.getPropertyValue(endpoint, "delayExpression", SpelExpression.class).getExpressionString())
                    .isEqualTo("42");
    mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.NON_PERSISTENT);
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isTrue();
    verifyFooRequestProducer(endpoint);
    channel.send(new GenericMessage<>("foo"));
    org.springframework.amqp.core.Message received = new RabbitTemplate(this.rabbitAvailableRule.getResource())
            .receive("foo.props.0.prodPropsRequired-0", 10_000);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedDelay()).isEqualTo(42);

    producerBinding.unbind();
    assertThat(endpoint.isRunning()).isFalse();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    RabbitTestBinder binder = getBinder();

    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setDurableSubscription(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    DirectChannel moduleInputChannel = createBindableChannel("input",
            createConsumerBindingProperties(consumerProperties));
    moduleInputChannel.setBeanName("durableTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override/* w w w . jav a  2s .  c  o m*/
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("durabletest.0", "tgroup", moduleInputChannel,
            consumerProperties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend(TEST_PREFIX + "durabletest.0", "", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "durabletest.0.tgroup.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();
    assertThat(admin.getQueueProperties(TEST_PREFIX + "durabletest.0.tgroup.dlq")).isNotNull();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testAutoBindDLQ() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.getExtension().setDurableSubscription(true);
    BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties);
    DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties);
    moduleInputChannel.setBeanName("dlqTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override//from w  w w . j ava  2 s. c o m
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("dlqtest", "default", moduleInputChannel,
            consumerProperties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("", TEST_PREFIX + "dlqtest.default", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "dlqtest.default.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();

    ApplicationContext context = TestUtils.getPropertyValue(binder,
            "binder.provisioningProvider.autoDeclareContext", ApplicationContext.class);
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq")).isFalse();
}

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 ww .  j av a  2 s  .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  ww.java2 s.com*/
    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  a v  a  2  s .  c  om*/
    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  w  w  w .j  av a 2 s.  c  om

    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.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Override
public Spy spyOn(final String queue) {
    final RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setAfterReceivePostProcessors(new DelegatingDecompressingPostProcessor());
    return new Spy() {

        @Override// w  w w.j  av  a  2  s.  c  o m
        public Object receive(boolean expectNull) throws Exception {
            if (expectNull) {
                Thread.sleep(50);
                return template.receiveAndConvert(new RabbitConsumerProperties().getPrefix() + queue);
            }
            Object bar = null;
            int n = 0;
            while (n++ < 100 && bar == null) {
                bar = template.receiveAndConvert(new RabbitConsumerProperties().getPrefix() + queue);
                Thread.sleep(100);
            }
            assertThat(n).isLessThan(100).withFailMessage("Message did not arrive in RabbitMQ");
            return bar;
        }

    };
}

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.co m
    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();
}