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

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

Introduction

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

Prototype

public final void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) 

Source Link

Document

Flag controlling the behaviour of the container with respect to message acknowledgement.

Usage

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQBuilder.java

@Override
public Object invokeMethod(String methodName, Object args) {
    if (CONSUME.equals(methodName)) {
        Consume consume = new Consume();
        SimpleMessageListenerContainer listenerContainer = consume.getListenerContainer();
        Object[] params = (Object[]) args;
        for (Object param : params) {
            if (param instanceof Map) {
                Map paramMap = (Map) param;

                if (paramMap.containsKey(ON_MESSAGE)) {
                    Object onMessage = paramMap.get(ON_MESSAGE);
                    if (onMessage instanceof String) {
                        consume.setEventName((String) onMessage);
                    } else if (onMessage instanceof Closure) {
                        consume.setDelegate((Closure) onMessage);
                    } else if (onMessage instanceof MessageListener) {
                        listenerContainer.setMessageListener(onMessage);
                    } else {
                        listenerContainer.setMessageListener(new MessageListenerAdapter(onMessage));
                    }//w w w.j  a  va2  s .c o m
                }

                if (paramMap.containsKey(ACK)) {
                    AcknowledgeMode mode = AcknowledgeMode.valueOf(paramMap.get(ACK).toString().toUpperCase());
                    listenerContainer.setAcknowledgeMode(mode);
                } else {
                    listenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
                }

            } else if (param instanceof Closure) {
                consume.setDelegate((Closure) param);
            }
        }
        listenerContainer.setQueues(currentQueue);
        listenerContainer.afterPropertiesSet();
        listenerContainer.start();
        listenerContainers.add(listenerContainer);

        return super.invokeMethod(methodName, consume);
    } else if (PUBLISH.equals(methodName)) {
        Publish publish = new Publish();
        publish.invokeMethod(CALL, args);
        return super.invokeMethod(methodName, publish);
    }

    return super.invokeMethod(methodName, args);
}

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));
    }/* ww w .  ja v a2 s  .  c  om*/
    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.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();//  w w  w  . ja  v  a2  s. co m
    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 2 s . co  m
    container.stop();
    singleConnectionFactory.destroy();
}

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);//from  w  w  w. j  a va  2s.  c o 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.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   ww  w  .  j  a  v  a2  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);
    }
}