Example usage for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer setChannelTransacted

List of usage examples for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer setChannelTransacted

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer setChannelTransacted.

Prototype

public void setChannelTransacted(boolean transactional) 

Source Link

Document

Flag to indicate that channels created by this component will be transactional.

Usage

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

private void doTest(int concurrentConsumers, ContainerConfigurer configurer) {
    int messageCount = 10;
    RabbitTemplate template = new RabbitTemplate();
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setChannelCacheSize(concurrentConsumers);
    connectionFactory.setPort(BrokerTestUtils.getPort());
    template.setConnectionFactory(connectionFactory);
    SimpleMessageConverter messageConverter = new SimpleMessageConverter();
    messageConverter.setCreateMessageIds(true);
    template.setMessageConverter(messageConverter);
    for (int i = 0; i < messageCount; i++) {
        template.convertAndSend(queue1.getName(), new Integer(i));
        template.convertAndSend(queue2.getName(), new Integer(i));
    }//from w  w w  .j  a v  a2 s .  co m
    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    final CountDownLatch latch = new CountDownLatch(messageCount * 2);
    PojoListener listener = new PojoListener(latch);
    container.setMessageListener(new MessageListenerAdapter(listener));
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    container.setChannelTransacted(true);
    container.setConcurrentConsumers(concurrentConsumers);
    configurer.configure(container);
    container.afterPropertiesSet();
    container.start();
    try {
        int timeout = Math.min(1 + messageCount / concurrentConsumers, 30);
        boolean waited = latch.await(timeout, TimeUnit.SECONDS);
        logger.info("All messages recovered: " + waited);
        assertEquals(concurrentConsumers, container.getActiveConsumerCount());
        assertTrue("Timed out waiting for messages", waited);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException("unexpected interruption");
    } finally {
        container.shutdown();
        assertEquals(0, container.getActiveConsumerCount());
    }
    assertNull(template.receiveAndConvert(queue1.getName()));
    assertNull(template.receiveAndConvert(queue2.getName()));
}

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

private void testChangeConsumerCountGuts(boolean transacted) throws Exception {
    final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost");
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
    try {//w  w w  .  j  a v a 2 s. c o  m
        container.setMessageListener(new MessageListenerAdapter(this));
        container.setQueueNames("foo");
        container.setAutoStartup(false);
        container.setConcurrentConsumers(2);
        container.setChannelTransacted(transacted);
        container.afterPropertiesSet();
        assertEquals(2, ReflectionTestUtils.getField(container, "concurrentConsumers"));
        container.start();
        waitForNConsumers(container, 2);
        container.setConcurrentConsumers(1);
        waitForNConsumers(container, 1);
        container.setMaxConcurrentConsumers(3);
        RabbitTemplate template = new RabbitTemplate(singleConnectionFactory);
        for (int i = 0; i < 20; i++) {
            template.convertAndSend("foo", "foo");
        }
        waitForNConsumers(container, 2); // increased consumers due to work
        waitForNConsumers(container, 1, 20000); // should stop the extra consumer after 10 seconds idle
        container.setConcurrentConsumers(3);
        waitForNConsumers(container, 3);
        container.stop();
        waitForNConsumers(container, 0);
        singleConnectionFactory.destroy();
    } finally {
        container.stop();
    }
}

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

@Test
public void testChannelTransactedOverriddenWhenTxManager() throws Exception {
    final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost");
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
    container.setMessageListener(new MessageListenerAdapter(this));
    container.setQueueNames("foo");
    container.setChannelTransacted(false);
    container.setTransactionManager(new TestTransactionManager());
    container.afterPropertiesSet();/*from ww w .  j av  a 2 s.  c  o  m*/
    assertTrue(TestUtils.getPropertyValue(container, "transactional", Boolean.class));
    container.stop();
    singleConnectionFactory.destroy();
}

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

@Test
public void testInconsistentTransactionConfiguration() throws Exception {
    final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost");
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
    container.setMessageListener(new MessageListenerAdapter(this));
    container.setQueueNames("foo");
    container.setChannelTransacted(false);
    container.setAcknowledgeMode(AcknowledgeMode.NONE);
    container.setTransactionManager(new TestTransactionManager());
    expectedException.expect(IllegalStateException.class);
    container.afterPropertiesSet();//from w w w.ja  v  a2  s .c om
    container.stop();
    singleConnectionFactory.destroy();
}

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

@Test
public void testInconsistentAcknowledgeConfiguration() throws Exception {
    final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost");
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
    container.setMessageListener(new MessageListenerAdapter(this));
    container.setQueueNames("foo");
    container.setChannelTransacted(true);
    container.setAcknowledgeMode(AcknowledgeMode.NONE);
    expectedException.expect(IllegalStateException.class);
    container.afterPropertiesSet();//from   w  w w. j  a v a 2s .c  om
    container.stop();
    singleConnectionFactory.destroy();
}

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  ww . j a v a 2 s  . co  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);
    }
}