Example usage for org.springframework.amqp.rabbit.retry RejectAndDontRequeueRecoverer RejectAndDontRequeueRecoverer

List of usage examples for org.springframework.amqp.rabbit.retry RejectAndDontRequeueRecoverer RejectAndDontRequeueRecoverer

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.retry RejectAndDontRequeueRecoverer RejectAndDontRequeueRecoverer.

Prototype

RejectAndDontRequeueRecoverer

Source Link

Usage

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test//w w w.j av a 2 s.  c om
public void testWithId() throws Exception {
    // 2 messages; each retried twice by retry interceptor
    this.latch = new CountDownLatch(6);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setMessageListener(new MessageListenerAdapter(new POJO()));
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);
    fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer());

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    messageProperties.setMessageId("foo");
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    template.send("retry.test.exchange", "retry.test.binding", message);
    template.send("retry.test.exchange", "retry.test.binding", message);
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class);
        verify(cache, times(6)).put(putCaptor.capture(), any(RetryContext.class));
        verify(cache, times(6)).get(getCaptor.capture());
        verify(cache, atLeast(2)).remove(removeCaptor.capture());
        verify(cache, atMost(4)).remove(removeCaptor.capture());
        logger.debug("puts:" + putCaptor.getAllValues());
        logger.debug("gets:" + putCaptor.getAllValues());
        logger.debug("removes:" + removeCaptor.getAllValues());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java

@SuppressWarnings("rawtypes")
@Test/*  w  ww. jav  a2s .c o m*/
public void testWithIdAndSuccess() throws Exception {
    // 2 messages; each retried twice by retry interceptor
    this.latch = new CountDownLatch(6);
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml",
            this.getClass());
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    final Set<String> processed = new HashSet<>();
    final CountDownLatch latch = new CountDownLatch(4);
    container.setMessageListener(m -> {
        latch.countDown();
        if (!processed.contains(m.getMessageProperties().getMessageId())) {
            processed.add(m.getMessageProperties().getMessageId());
            throw new RuntimeException("fail");
        }
    });
    container.setQueueNames("retry.test.queue");

    StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean();

    // use an external template so we can share his cache
    RetryTemplate retryTemplate = new RetryTemplate();
    RetryContextCache cache = spy(new MapRetryContextCache());
    retryTemplate.setRetryContextCache(cache);
    fb.setRetryOperations(retryTemplate);
    fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer());

    Advice retryInterceptor = fb.getObject();
    container.setAdviceChain(retryInterceptor);
    container.start();

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    messageProperties.setMessageId("foo");
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    template.send("retry.test.exchange", "retry.test.binding", message);
    messageProperties.setMessageId("bar");
    template.send("retry.test.exchange", "retry.test.binding", message);
    try {
        assertTrue(latch.await(30, TimeUnit.SECONDS));
        Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map");
        int n = 0;
        while (n++ < 100 && map.size() != 0) {
            Thread.sleep(100);
        }
        ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class);
        verify(cache, times(2)).put(putCaptor.capture(), any(RetryContext.class));
        verify(cache, times(2)).get(getCaptor.capture());
        verify(cache, atLeast(2)).remove(removeCaptor.capture());
        verify(cache, atMost(4)).remove(removeCaptor.capture());
        logger.debug("puts:" + putCaptor.getAllValues());
        logger.debug("gets:" + putCaptor.getAllValues());
        logger.debug("removes:" + removeCaptor.getAllValues());
        assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size());
    } finally {
        container.stop();
        ctx.close();
    }
}

From source file:org.springframework.xd.dirt.integration.rabbit.RabbitMessageBus.java

private void doRegisterConsumer(String name, MessageChannel moduleInputChannel, Queue queue,
        RabbitPropertiesAccessor properties, boolean isPubSub) {
    // Fix for XD-2503
    // Temporarily overrides the thread context classloader with the one where the SimpleMessageListenerContainer is defined
    // This allows for the proxying that happens while initializing the SimpleMessageListenerContainer to work correctly
    ClassLoader originalClassloader = Thread.currentThread().getContextClassLoader();
    try {/*from   w  w  w.ja v a  2 s.c o m*/
        ClassUtils.overrideThreadContextClassLoader(SimpleMessageListenerContainer.class.getClassLoader());
        SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
                this.connectionFactory);
        listenerContainer.setAcknowledgeMode(properties.getAcknowledgeMode(this.defaultAcknowledgeMode));
        listenerContainer.setChannelTransacted(properties.getTransacted(this.defaultChannelTransacted));
        listenerContainer
                .setDefaultRequeueRejected(properties.getRequeueRejected(this.defaultDefaultRequeueRejected));
        if (!isPubSub) {
            int concurrency = properties.getConcurrency(this.defaultConcurrency);
            concurrency = concurrency > 0 ? concurrency : 1;
            listenerContainer.setConcurrentConsumers(concurrency);
            int maxConcurrency = properties.getMaxConcurrency(this.defaultMaxConcurrency);
            if (maxConcurrency > concurrency) {
                listenerContainer.setMaxConcurrentConsumers(maxConcurrency);
            }
        }
        listenerContainer.setPrefetchCount(properties.getPrefetchCount(this.defaultPrefetchCount));
        listenerContainer.setTxSize(properties.getTxSize(this.defaultTxSize));
        listenerContainer.setTaskExecutor(new SimpleAsyncTaskExecutor(queue.getName() + "-"));
        listenerContainer.setQueues(queue);
        int maxAttempts = properties.getMaxAttempts(this.defaultMaxAttempts);
        if (maxAttempts > 1) {
            RetryOperationsInterceptor retryInterceptor = RetryInterceptorBuilder.stateless()
                    .maxAttempts(maxAttempts)
                    .backOffOptions(properties.getBackOffInitialInterval(this.defaultBackOffInitialInterval),
                            properties.getBackOffMultiplier(this.defaultBackOffMultiplier),
                            properties.getBackOffMaxInterval(this.defaultBackOffMaxInterval))
                    .recoverer(new RejectAndDontRequeueRecoverer()).build();
            listenerContainer.setAdviceChain(new Advice[] { retryInterceptor });
        }
        listenerContainer.setAfterReceivePostProcessors(this.decompressingPostProcessor);
        listenerContainer.setMessagePropertiesConverter(RabbitMessageBus.inboundMessagePropertiesConverter);
        listenerContainer.afterPropertiesSet();
        AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
        adapter.setBeanFactory(this.getBeanFactory());
        DirectChannel bridgeToModuleChannel = new DirectChannel();
        bridgeToModuleChannel.setBeanFactory(this.getBeanFactory());
        bridgeToModuleChannel.setBeanName(name + ".bridge");
        adapter.setOutputChannel(bridgeToModuleChannel);
        adapter.setBeanName("inbound." + name);
        DefaultAmqpHeaderMapper mapper = new DefaultAmqpHeaderMapper();
        mapper.setRequestHeaderNames(properties.getRequestHeaderPattens(this.defaultRequestHeaderPatterns));
        mapper.setReplyHeaderNames(properties.getReplyHeaderPattens(this.defaultReplyHeaderPatterns));
        adapter.setHeaderMapper(mapper);
        adapter.afterPropertiesSet();
        Binding consumerBinding = Binding.forConsumer(name, adapter, moduleInputChannel, properties);
        addBinding(consumerBinding);
        ReceivingHandler convertingBridge = new ReceivingHandler();
        convertingBridge.setOutputChannel(moduleInputChannel);
        convertingBridge.setBeanName(name + ".convert.bridge");
        convertingBridge.afterPropertiesSet();
        bridgeToModuleChannel.subscribe(convertingBridge);
        consumerBinding.start();
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassloader);
    }
}