Example usage for org.springframework.amqp.core AcknowledgeMode AUTO

List of usage examples for org.springframework.amqp.core AcknowledgeMode AUTO

Introduction

In this page you can find the example usage for org.springframework.amqp.core AcknowledgeMode AUTO.

Prototype

AcknowledgeMode AUTO

To view the source code for org.springframework.amqp.core AcknowledgeMode AUTO.

Click Source Link

Document

Auto - the container will issue the ack/nack based on whether the listener returns normally, or throws an exception.

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.  ja v  a 2s  .com
                }

                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));
    }//from   w  w w . java  2s. c  o  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.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   www  . java  2s  . c  om*/

    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 testConsumerProperties() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setRequeueRejected(true);
    properties.getExtension().setTransacted(true);
    properties.getExtension().setExclusive(true);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("props.0", null,
            createBindableChannel("input", new BindingProperties()), properties);
    Lifecycle endpoint = extractEndpoint(consumerBinding);
    SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer",
            SimpleMessageListenerContainer.class);
    assertThat(container.getAcknowledgeMode()).isEqualTo(AcknowledgeMode.AUTO);
    assertThat(container.getQueueNames()[0]).startsWith(properties.getExtension().getPrefix());
    assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")).isEqualTo(1);
    assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")).isNull();
    assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)).isTrue();
    assertThat(TestUtils.getPropertyValue(container, "prefetchCount")).isEqualTo(1);
    assertThat(TestUtils.getPropertyValue(container, "txSize")).isEqualTo(1);
    RetryTemplate retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", RetryTemplate.class);
    assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")).isEqualTo(3);
    assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")).isEqualTo(1000L);
    assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")).isEqualTo(10000L);
    assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")).isEqualTo(2.0);
    consumerBinding.unbind();//from   w ww . j av  a2s  .  c o m
    assertThat(endpoint.isRunning()).isFalse();

    properties = createConsumerProperties();
    properties.getExtension().setAcknowledgeMode(AcknowledgeMode.NONE);
    properties.setBackOffInitialInterval(2000);
    properties.setBackOffMaxInterval(20000);
    properties.setBackOffMultiplier(5.0);
    properties.setConcurrency(2);
    properties.setMaxAttempts(23);
    properties.getExtension().setMaxConcurrency(3);
    properties.getExtension().setPrefix("foo.");
    properties.getExtension().setPrefetch(20);
    properties.getExtension().setHeaderPatterns(new String[] { "foo" });
    properties.getExtension().setTxSize(10);
    properties.setInstanceIndex(0);
    consumerBinding = binder.bindConsumer("props.0", "test",
            createBindableChannel("input", new BindingProperties()), properties);

    endpoint = extractEndpoint(consumerBinding);
    container = verifyContainer(endpoint);

    assertThat(container.getQueueNames()[0]).isEqualTo("foo.props.0.test");

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

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

@Test
public void testConsumerProperties() throws Exception {
    MessageBus bus = getMessageBus();/*from  www .  j a  v a  2s .  c o m*/
    Properties properties = new Properties();
    properties.put("transacted", "true"); // test transacted with defaults; not allowed with ackmode NONE
    bus.bindConsumer("props.0", new DirectChannel(), properties);
    @SuppressWarnings("unchecked")
    List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class);
    assertEquals(1, bindings.size());
    AbstractEndpoint endpoint = bindings.get(0).getEndpoint();
    SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer",
            SimpleMessageListenerContainer.class);
    assertEquals(AcknowledgeMode.AUTO, container.getAcknowledgeMode());
    assertEquals("xdbus.props.0", container.getQueueNames()[0]);
    assertTrue(TestUtils.getPropertyValue(container, "transactional", Boolean.class));
    assertEquals(1, TestUtils.getPropertyValue(container, "concurrentConsumers"));
    assertNull(TestUtils.getPropertyValue(container, "maxConcurrentConsumers"));
    assertTrue(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class));
    assertEquals(1, TestUtils.getPropertyValue(container, "prefetchCount"));
    assertEquals(1, TestUtils.getPropertyValue(container, "txSize"));
    Advice retry = TestUtils.getPropertyValue(container, "adviceChain", Advice[].class)[0];
    assertEquals(3, TestUtils.getPropertyValue(retry, "retryOperations.retryPolicy.maxAttempts"));
    assertEquals(1000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.initialInterval"));
    assertEquals(10000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.maxInterval"));
    assertEquals(2.0, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.multiplier"));
    bus.unbindConsumers("props.0");
    assertEquals(0, bindings.size());

    properties = new Properties();
    properties.put("ackMode", "NONE");
    properties.put("backOffInitialInterval", "2000");
    properties.put("backOffMaxInterval", "20000");
    properties.put("backOffMultiplier", "5.0");
    properties.put("concurrency", "2");
    properties.put("maxAttempts", "23");
    properties.put("maxConcurrency", "3");
    properties.put("prefix", "foo.");
    properties.put("prefetch", "20");
    properties.put("requestHeaderPatterns", "foo");
    properties.put("requeue", "false");
    properties.put("txSize", "10");
    properties.put("partitionIndex", 0);
    bus.bindConsumer("props.0", new DirectChannel(), properties);

    @SuppressWarnings("unchecked")
    List<Binding> bindingsNow = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class);
    assertEquals(1, bindingsNow.size());
    endpoint = bindingsNow.get(0).getEndpoint();
    container = verifyContainer(endpoint);

    assertEquals("foo.props.0", container.getQueueNames()[0]);

    try {
        bus.bindPubSubConsumer("dummy", null, properties);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(),
                allOf(containsString("RabbitMessageBus does not support consumer properties: "),
                        containsString("partitionIndex"), containsString("concurrency"),
                        containsString(" for dummy.")));
    }
    try {
        bus.bindConsumer("queue:dummy", null, properties);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertEquals("RabbitMessageBus does not support consumer property: partitionIndex for queue:dummy.",
                e.getMessage());
    }

    bus.unbindConsumers("props.0");
    assertEquals(0, bindingsNow.size());
}