Search in sources :

Example 1 with RabbitConsumerProperties

use of org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties in project spring-cloud-stream by spring-cloud.

the class RabbitBinderTests method testConsumerPropertiesWithUserInfrastructureCustomQueueArgs.

@Test
public void testConsumerPropertiesWithUserInfrastructureCustomQueueArgs() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    RabbitConsumerProperties extProps = properties.getExtension();
    extProps.setExchangeType(ExchangeTypes.DIRECT);
    extProps.setExchangeDurable(false);
    extProps.setExchangeAutoDelete(true);
    extProps.setBindingRoutingKey("foo");
    extProps.setExpires(30_000);
    extProps.setLazy(true);
    extProps.setMaxLength(10_000);
    extProps.setMaxLengthBytes(100_000);
    extProps.setMaxPriority(10);
    extProps.setOverflowBehavior("drop-head");
    extProps.setTtl(2_000);
    extProps.setAutoBindDlq(true);
    extProps.setDeadLetterQueueName("customDLQ");
    extProps.setDeadLetterExchange("customDLX");
    extProps.setDeadLetterExchangeType(ExchangeTypes.TOPIC);
    extProps.setDeadLetterRoutingKey("customDLRK");
    extProps.setDlqDeadLetterExchange("propsUser3");
    // GH-259 - if the next line was commented, the test failed.
    extProps.setDlqDeadLetterRoutingKey("propsUser3");
    extProps.setDlqExpires(60_000);
    extProps.setDlqLazy(true);
    extProps.setDlqMaxLength(20_000);
    extProps.setDlqMaxLengthBytes(40_000);
    extProps.setDlqOverflowBehavior("reject-publish");
    extProps.setDlqMaxPriority(8);
    extProps.setDlqTtl(1_000);
    extProps.setConsumerTagPrefix("testConsumerTag");
    extProps.setExclusive(true);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("propsUser3", "infra", createBindableChannel("input", new BindingProperties()), properties);
    Lifecycle endpoint = extractEndpoint(consumerBinding);
    SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", SimpleMessageListenerContainer.class);
    assertThat(container.isRunning()).isTrue();
    Client client = new Client(adminUri());
    List<BindingInfo> bindings = client.getBindingsBySource("/", "propsUser3");
    int n = 0;
    while (n++ < 100 && bindings == null || bindings.size() < 1) {
        Thread.sleep(100);
        bindings = client.getBindingsBySource("/", "propsUser3");
    }
    assertThat(bindings.size()).isEqualTo(1);
    assertThat(bindings.get(0).getSource()).isEqualTo("propsUser3");
    assertThat(bindings.get(0).getDestination()).isEqualTo("propsUser3.infra");
    assertThat(bindings.get(0).getRoutingKey()).isEqualTo("foo");
    bindings = client.getBindingsBySource("/", "customDLX");
    n = 0;
    while (n++ < 100 && bindings == null || bindings.size() < 1) {
        Thread.sleep(100);
        bindings = client.getBindingsBySource("/", "customDLX");
    }
    // assertThat(bindings.size()).isEqualTo(1);
    assertThat(bindings.get(0).getSource()).isEqualTo("customDLX");
    assertThat(bindings.get(0).getDestination()).isEqualTo("customDLQ");
    assertThat(bindings.get(0).getRoutingKey()).isEqualTo("customDLRK");
    ExchangeInfo exchange = client.getExchange("/", "propsUser3");
    n = 0;
    while (n++ < 100 && exchange == null) {
        Thread.sleep(100);
        exchange = client.getExchange("/", "propsUser3");
    }
    assertThat(exchange.getType()).isEqualTo("direct");
    assertThat(exchange.isDurable()).isEqualTo(false);
    assertThat(exchange.isAutoDelete()).isEqualTo(true);
    exchange = client.getExchange("/", "customDLX");
    n = 0;
    while (n++ < 100 && exchange == null) {
        Thread.sleep(100);
        exchange = client.getExchange("/", "customDLX");
    }
    assertThat(exchange.getType()).isEqualTo("topic");
    assertThat(exchange.isDurable()).isEqualTo(true);
    assertThat(exchange.isAutoDelete()).isEqualTo(false);
    QueueInfo queue = client.getQueue("/", "propsUser3.infra");
    n = 0;
    while (n++ < 100 && queue == null || queue.getConsumerCount() == 0) {
        Thread.sleep(100);
        queue = client.getQueue("/", "propsUser3.infra");
    }
    assertThat(queue).isNotNull();
    Map<String, Object> args = queue.getArguments();
    assertThat(args.get("x-expires")).isEqualTo(30_000);
    assertThat(args.get("x-max-length")).isEqualTo(10_000);
    assertThat(args.get("x-max-length-bytes")).isEqualTo(100_000);
    assertThat(args.get("x-overflow")).isEqualTo("drop-head");
    assertThat(args.get("x-max-priority")).isEqualTo(10);
    assertThat(args.get("x-message-ttl")).isEqualTo(2_000);
    assertThat(args.get("x-dead-letter-exchange")).isEqualTo("customDLX");
    assertThat(args.get("x-dead-letter-routing-key")).isEqualTo("customDLRK");
    assertThat(args.get("x-queue-mode")).isEqualTo("lazy");
    assertThat(queue.getExclusiveConsumerTag()).isEqualTo("testConsumerTag#0");
    queue = client.getQueue("/", "customDLQ");
    n = 0;
    while (n++ < 100 && queue == null) {
        Thread.sleep(100);
        queue = client.getQueue("/", "customDLQ");
    }
    assertThat(queue).isNotNull();
    args = queue.getArguments();
    assertThat(args.get("x-expires")).isEqualTo(60_000);
    assertThat(args.get("x-max-length")).isEqualTo(20_000);
    assertThat(args.get("x-max-length-bytes")).isEqualTo(40_000);
    assertThat(args.get("x-overflow")).isEqualTo("reject-publish");
    assertThat(args.get("x-max-priority")).isEqualTo(8);
    assertThat(args.get("x-message-ttl")).isEqualTo(1_000);
    assertThat(args.get("x-dead-letter-exchange")).isEqualTo("propsUser3");
    assertThat(args.get("x-dead-letter-routing-key")).isEqualTo("propsUser3");
    assertThat(args.get("x-queue-mode")).isEqualTo("lazy");
    consumerBinding.unbind();
    assertThat(container.isRunning()).isFalse();
    verifyAutoDeclareContextClear(binder);
}
Also used : QueueInfo(com.rabbitmq.http.client.domain.QueueInfo) RabbitConsumerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties) BindingProperties(org.springframework.cloud.stream.config.BindingProperties) Lifecycle(org.springframework.context.Lifecycle) SimpleMessageListenerContainer(org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer) LongString(com.rabbitmq.client.LongString) ExchangeInfo(com.rabbitmq.http.client.domain.ExchangeInfo) AmqpOutboundEndpoint(org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint) MessageChannel(org.springframework.messaging.MessageChannel) BindingInfo(com.rabbitmq.http.client.domain.BindingInfo) Client(com.rabbitmq.http.client.Client) Test(org.junit.jupiter.api.Test)

Example 2 with RabbitConsumerProperties

use of org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties in project spring-cloud-stream by spring-cloud.

the class RabbitBinderTests method testSendAndReceiveBad.

@Test
public void testSendAndReceiveBad(TestInfo testInfo) throws Exception {
    RabbitTestBinder binder = getBinder();
    final AtomicReference<AsyncConsumerStartedEvent> event = new AtomicReference<>();
    binder.getApplicationContext().addApplicationListener((ApplicationListener<AsyncConsumerStartedEvent>) e -> event.set(e));
    DirectChannel moduleOutputChannel = createBindableChannel("output", new BindingProperties());
    DirectChannel moduleInputChannel = createBindableChannel("input", new BindingProperties());
    Binding<MessageChannel> producerBinding = binder.bindProducer("bad.0", moduleOutputChannel, createProducerProperties(testInfo));
    assertThat(TestUtils.getPropertyValue(producerBinding, "lifecycle.headersMappedLast", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(producerBinding, "lifecycle.amqpTemplate.messageConverter").getClass().getName()).contains("Passthrough");
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProps = createConsumerProperties();
    consumerProps.getExtension().setContainerType(ContainerType.DIRECT);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("bad.0", "test", moduleInputChannel, consumerProps);
    assertThat(TestUtils.getPropertyValue(consumerBinding, "lifecycle.messageConverter").getClass().getName()).contains("Passthrough");
    assertThat(TestUtils.getPropertyValue(consumerBinding, "lifecycle.messageListenerContainer")).isInstanceOf(DirectMessageListenerContainer.class);
    Message<?> message = MessageBuilder.withPayload("bad".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build();
    final CountDownLatch latch = new CountDownLatch(3);
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            latch.countDown();
            throw new RuntimeException("bad");
        }
    });
    moduleOutputChannel.send(message);
    assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
    assertThat(event.get()).isNotNull();
    producerBinding.unbind();
    consumerBinding.unbind();
    verifyAutoDeclareContextClear(binder);
}
Also used : Arrays(java.util.Arrays) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Disabled(org.junit.jupiter.api.Disabled) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Map(java.util.Map) ExtendedConsumerProperties(org.springframework.cloud.stream.binder.ExtendedConsumerProperties) PartitionSelectorStrategy(org.springframework.cloud.stream.binder.PartitionSelectorStrategy) RabbitMQContainer(org.testcontainers.containers.RabbitMQContainer) BatchingStrategy(org.springframework.amqp.rabbit.batch.BatchingStrategy) DirectMessageListenerContainer(org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer) ConfirmType(org.springframework.amqp.rabbit.connection.CachingConnectionFactory.ConfirmType) PrintWriter(java.io.PrintWriter) DirectExchange(org.springframework.amqp.core.DirectExchange) RabbitTestSupport(org.springframework.cloud.stream.binder.test.junit.rabbit.RabbitTestSupport) ExchangeTypes(org.springframework.amqp.core.ExchangeTypes) RabbitExchangeQueueProvisioner(org.springframework.cloud.stream.binder.rabbit.provisioning.RabbitExchangeQueueProvisioner) Set(java.util.Set) BinderException(org.springframework.cloud.stream.binder.BinderException) QueueInfo(com.rabbitmq.http.client.domain.QueueInfo) MessageChannel(org.springframework.messaging.MessageChannel) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Assertions.fail(org.assertj.core.api.Assertions.fail) MessageHandler(org.springframework.messaging.MessageHandler) BindingProperties(org.springframework.cloud.stream.config.BindingProperties) Mockito.mock(org.mockito.Mockito.mock) Spy(org.springframework.cloud.stream.binder.Spy) ConsumerDestination(org.springframework.cloud.stream.provisioning.ConsumerDestination) CorrelationData(org.springframework.amqp.rabbit.connection.CorrelationData) Mockito.spy(org.mockito.Mockito.spy) Constructor(java.lang.reflect.Constructor) ImmediateAcknowledgeAmqpException(org.springframework.amqp.ImmediateAcknowledgeAmqpException) ArrayList(java.util.ArrayList) CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) RabbitAdmin(org.springframework.amqp.rabbit.core.RabbitAdmin) Message(org.springframework.messaging.Message) AsyncConsumerStartedEvent(org.springframework.amqp.rabbit.listener.AsyncConsumerStartedEvent) RepublishMessageRecoverer(org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer) StringWriter(java.io.StringWriter) MessageHeaders(org.springframework.messaging.MessageHeaders) Lifecycle(org.springframework.context.Lifecycle) TestUtils(org.springframework.amqp.utils.test.TestUtils) PartitionCapableBinderTests(org.springframework.cloud.stream.binder.PartitionCapableBinderTests) RabbitConsumerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties) PollableSource(org.springframework.cloud.stream.binder.PollableSource) AmqpIOException(org.springframework.amqp.AmqpIOException) PartitionKeyExtractorStrategy(org.springframework.cloud.stream.binder.PartitionKeyExtractorStrategy) LongString(com.rabbitmq.client.LongString) RetryTemplate(org.springframework.retry.support.RetryTemplate) AcknowledgeMode(org.springframework.amqp.core.AcknowledgeMode) AmqpTemplate(org.springframework.amqp.core.AmqpTemplate) MessageDeliveryMode(org.springframework.amqp.core.MessageDeliveryMode) SimpleMessageListenerContainer(org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BindingInfo(com.rabbitmq.http.client.domain.BindingInfo) AbstractMessageListenerContainer(org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer) ByteBuffer(java.nio.ByteBuffer) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) ExchangeInfo(com.rabbitmq.http.client.domain.ExchangeInfo) ValueExpression(org.springframework.integration.expression.ValueExpression) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) Collection(java.util.Collection) UUID(java.util.UUID) Deflater(java.util.zip.Deflater) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) BridgeHandler(org.springframework.integration.handler.BridgeHandler) NackedAmqpMessageException(org.springframework.integration.amqp.support.NackedAmqpMessageException) List(java.util.List) SpelExpression(org.springframework.expression.spel.standard.SpelExpression) Confirm(org.springframework.amqp.rabbit.connection.CorrelationData.Confirm) TopicExchange(org.springframework.amqp.core.TopicExchange) DirectChannel(org.springframework.integration.channel.DirectChannel) Client(com.rabbitmq.http.client.Client) RabbitProperties(org.springframework.boot.autoconfigure.amqp.RabbitProperties) QuorumConfig(org.springframework.cloud.stream.binder.rabbit.properties.RabbitCommonProperties.QuorumConfig) BinderHeaders(org.springframework.cloud.stream.binder.BinderHeaders) DefaultPollableMessageSource(org.springframework.cloud.stream.binder.DefaultPollableMessageSource) QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) DestinationType(org.springframework.amqp.core.Binding.DestinationType) ConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) ContainerType(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties.ContainerType) SubscribableChannel(org.springframework.messaging.SubscribableChannel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) MessageProperties(org.springframework.amqp.core.MessageProperties) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ExtendedProducerProperties(org.springframework.cloud.stream.binder.ExtendedProducerProperties) AtomicReference(java.util.concurrent.atomic.AtomicReference) ReturnedAmqpMessageException(org.springframework.integration.amqp.support.ReturnedAmqpMessageException) ChannelInterceptor(org.springframework.messaging.support.ChannelInterceptor) RequeueCurrentMessageException(org.springframework.cloud.stream.binder.RequeueCurrentMessageException) MessageBuilder(org.springframework.integration.support.MessageBuilder) BindingBuilder(org.springframework.amqp.core.BindingBuilder) Binding(org.springframework.cloud.stream.binder.Binding) ArgumentCaptor(org.mockito.ArgumentCaptor) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Queue(org.springframework.amqp.core.Queue) DelegatingDecompressingPostProcessor(org.springframework.amqp.support.postprocessor.DelegatingDecompressingPostProcessor) RabbitTemplate(org.springframework.amqp.rabbit.core.RabbitTemplate) RabbitProducerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitProducerProperties) Declarable(org.springframework.amqp.core.Declarable) MimeTypeUtils(org.springframework.util.MimeTypeUtils) Mockito.when(org.mockito.Mockito.when) ApplicationContext(org.springframework.context.ApplicationContext) RabbitUtils(org.springframework.amqp.rabbit.connection.RabbitUtils) IntegrationContextUtils(org.springframework.integration.context.IntegrationContextUtils) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) AmqpOutboundEndpoint(org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint) MessageBatch(org.springframework.amqp.rabbit.batch.MessageBatch) ReflectionUtils(org.springframework.util.ReflectionUtils) PartitionTestSupport(org.springframework.cloud.stream.binder.PartitionTestSupport) Log(org.apache.commons.logging.Log) AmqpHeaders(org.springframework.amqp.support.AmqpHeaders) AnonymousQueue(org.springframework.amqp.core.AnonymousQueue) GenericMessage(org.springframework.messaging.support.GenericMessage) Collections(java.util.Collections) RabbitConsumerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties) MessageHandler(org.springframework.messaging.MessageHandler) DirectChannel(org.springframework.integration.channel.DirectChannel) MessagingException(org.springframework.messaging.MessagingException) BindingProperties(org.springframework.cloud.stream.config.BindingProperties) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncConsumerStartedEvent(org.springframework.amqp.rabbit.listener.AsyncConsumerStartedEvent) MessageChannel(org.springframework.messaging.MessageChannel) Test(org.junit.jupiter.api.Test)

Example 3 with RabbitConsumerProperties

use of org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties in project spring-cloud-stream by spring-cloud.

the class RabbitBinderTests method testMultiplexOnPartitionedConsumer.

@Test
public void testMultiplexOnPartitionedConsumer() throws Exception {
    final ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    RabbitTestSupport.RabbitProxy proxy = new RabbitTestSupport.RabbitProxy();
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost", proxy.getPort());
    final RabbitExchangeQueueProvisioner rabbitExchangeQueueProvisioner = new RabbitExchangeQueueProvisioner(cf);
    consumerProperties.setMultiplex(true);
    consumerProperties.setPartitioned(true);
    consumerProperties.setInstanceIndexList(Arrays.asList(1, 2, 3));
    final ConsumerDestination consumerDestination = rabbitExchangeQueueProvisioner.provisionConsumerDestination("foo", "boo", consumerProperties);
    final String name = consumerDestination.getName();
    assertThat(name).isEqualTo("foo.boo-1,foo.boo-2,foo.boo-3");
}
Also used : RabbitExchangeQueueProvisioner(org.springframework.cloud.stream.binder.rabbit.provisioning.RabbitExchangeQueueProvisioner) RabbitConsumerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties) RabbitTestSupport(org.springframework.cloud.stream.binder.test.junit.rabbit.RabbitTestSupport) CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) ConsumerDestination(org.springframework.cloud.stream.provisioning.ConsumerDestination) LongString(com.rabbitmq.client.LongString) Test(org.junit.jupiter.api.Test)

Example 4 with RabbitConsumerProperties

use of org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties in project spring-cloud-stream by spring-cloud.

the class RabbitBinderTests method testAutoBindDLQwithRepublishCorrelatedConfirms.

@SuppressWarnings("unchecked")
@Test
public void testAutoBindDLQwithRepublishCorrelatedConfirms() throws Exception {
    CachingConnectionFactory ccf = this.rabbitTestSupport.getResource();
    ccf.setPublisherReturns(true);
    ccf.setPublisherConfirmType(ConfirmType.CORRELATED);
    ccf.resetConnection();
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setRepublishToDlq(true);
    // disable retry
    consumerProperties.setMaxAttempts(1);
    consumerProperties.getExtension().setDurableSubscription(true);
    DirectChannel moduleInputChannel = createBindableChannel("input", createConsumerBindingProperties(consumerProperties));
    moduleInputChannel.setBeanName("dlqPubtestCorrelated");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("test");
        }
    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.dlqpubtestCorrelated", "foo", moduleInputChannel, consumerProperties);
    RabbitTemplate template = new RabbitTemplate(this.rabbitTestSupport.getResource());
    template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtestCorrelated.foo", "foo");
    template.setReceiveTimeout(10_000);
    org.springframework.amqp.core.Message deadLetter = template.receive(TEST_PREFIX + "foo.dlqpubtestCorrelated.foo.dlq");
    assertThat(deadLetter).isNotNull();
    assertThat(deadLetter.getBody()).isEqualTo("foo".getBytes());
    assertThat(deadLetter.getMessageProperties().getHeaders()).containsKey((RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE));
    List<Object> errorHandler = (List<Object>) TestUtils.getPropertyValue(consumerBinding, "lifecycle.errorChannel.dispatcher.handlers", Set.class).stream().filter(handler -> !handler.getClass().equals(BridgeHandler.class)).collect(Collectors.toList());
    assertThat(errorHandler).hasSize(1);
    assertThat(TestUtils.getPropertyValue(errorHandler.get(0), "confirmType", ConfirmType.class)).isEqualTo(ConfirmType.CORRELATED);
    consumerBinding.unbind();
    verifyAutoDeclareContextClear(binder);
}
Also used : RabbitTemplate(org.springframework.amqp.rabbit.core.RabbitTemplate) RabbitConsumerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties) MessageHandler(org.springframework.messaging.MessageHandler) DirectChannel(org.springframework.integration.channel.DirectChannel) MessagingException(org.springframework.messaging.MessagingException) MessageChannel(org.springframework.messaging.MessageChannel) CachingConnectionFactory(org.springframework.amqp.rabbit.connection.CachingConnectionFactory) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 5 with RabbitConsumerProperties

use of org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties in project spring-cloud-stream by spring-cloud.

the class RabbitBinderTests method testAutoBindDLQwithRepublish.

@Test
public void testAutoBindDLQwithRepublish() throws Exception {
    this.maxStackTraceSize = RabbitUtils.getMaxFrame(rabbitTestSupport.getResource()) - 20_000;
    assertThat(this.maxStackTraceSize).isGreaterThan(0);
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setRepublishToDlq(true);
    // disable retry
    consumerProperties.setMaxAttempts(1);
    consumerProperties.getExtension().setDurableSubscription(true);
    DirectChannel moduleInputChannel = createBindableChannel("input", createConsumerBindingProperties(consumerProperties));
    moduleInputChannel.setBeanName("dlqPubTest");
    RuntimeException exception = bigCause(new RuntimeException(BIG_EXCEPTION_MESSAGE));
    assertThat(getStackTraceAsString(exception).length()).isGreaterThan(this.maxStackTraceSize);
    AtomicBoolean dontRepublish = new AtomicBoolean();
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (dontRepublish.get()) {
                throw new ImmediateAcknowledgeAmqpException("testDontRepublish");
            }
            throw exception;
        }
    });
    consumerProperties.setMultiplex(true);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.dlqpubtest,foo.dlqpubtest2", "foo", moduleInputChannel, consumerProperties);
    RabbitTemplate template = new RabbitTemplate(this.rabbitTestSupport.getResource());
    template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest.foo", "foo");
    template.setReceiveTimeout(10_000);
    org.springframework.amqp.core.Message deadLetter = template.receive(TEST_PREFIX + "foo.dlqpubtest.foo.dlq");
    assertThat(deadLetter).isNotNull();
    assertThat(new String(deadLetter.getBody())).isEqualTo("foo");
    assertThat(deadLetter.getMessageProperties().getHeaders()).containsKey((RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE));
    assertThat(((LongString) deadLetter.getMessageProperties().getHeaders().get(RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE)).length()).isEqualTo(this.maxStackTraceSize);
    template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest2.foo", "bar");
    deadLetter = template.receive(TEST_PREFIX + "foo.dlqpubtest2.foo.dlq");
    assertThat(deadLetter).isNotNull();
    assertThat(new String(deadLetter.getBody())).isEqualTo("bar");
    assertThat(deadLetter.getMessageProperties().getHeaders()).containsKey(("x-exception-stacktrace"));
    dontRepublish.set(true);
    template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest2.foo", "baz");
    template.setReceiveTimeout(500);
    assertThat(template.receive(TEST_PREFIX + "foo.dlqpubtest2.foo.dlq")).isNull();
    consumerBinding.unbind();
    verifyAutoDeclareContextClear(binder);
}
Also used : RabbitTemplate(org.springframework.amqp.rabbit.core.RabbitTemplate) RabbitConsumerProperties(org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties) MessageHandler(org.springframework.messaging.MessageHandler) DirectChannel(org.springframework.integration.channel.DirectChannel) MessagingException(org.springframework.messaging.MessagingException) LongString(com.rabbitmq.client.LongString) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MessageChannel(org.springframework.messaging.MessageChannel) ImmediateAcknowledgeAmqpException(org.springframework.amqp.ImmediateAcknowledgeAmqpException) LongString(com.rabbitmq.client.LongString) Test(org.junit.jupiter.api.Test)

Aggregations

RabbitConsumerProperties (org.springframework.cloud.stream.binder.rabbit.properties.RabbitConsumerProperties)43 Test (org.junit.jupiter.api.Test)34 MessageChannel (org.springframework.messaging.MessageChannel)29 DirectChannel (org.springframework.integration.channel.DirectChannel)20 RabbitTemplate (org.springframework.amqp.rabbit.core.RabbitTemplate)19 MessageHandler (org.springframework.messaging.MessageHandler)19 MessagingException (org.springframework.messaging.MessagingException)16 RabbitProducerProperties (org.springframework.cloud.stream.binder.rabbit.properties.RabbitProducerProperties)15 BindingProperties (org.springframework.cloud.stream.config.BindingProperties)15 AmqpOutboundEndpoint (org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint)15 LongString (com.rabbitmq.client.LongString)14 SimpleMessageListenerContainer (org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer)13 ArrayList (java.util.ArrayList)12 List (java.util.List)11 ExtendedConsumerProperties (org.springframework.cloud.stream.binder.ExtendedConsumerProperties)11 ConsumerDestination (org.springframework.cloud.stream.provisioning.ConsumerDestination)11 QueueChannel (org.springframework.integration.channel.QueueChannel)11 ConnectionFactory (org.springframework.amqp.rabbit.connection.ConnectionFactory)10 Lifecycle (org.springframework.context.Lifecycle)10 CachingConnectionFactory (org.springframework.amqp.rabbit.connection.CachingConnectionFactory)9