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

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

Introduction

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

Prototype

public void setConcurrentConsumers(final int concurrentConsumers) 

Source Link

Document

Specify the number of concurrent consumers to create.

Usage

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

@Test
public void testListenFromAnonQueue() throws Exception {
    AnonymousQueue queue = new AnonymousQueue();
    CountDownLatch latch = new CountDownLatch(10);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
            template.getConnectionFactory());
    container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch)));
    container.setQueueNames(queue.getName());
    container.setConcurrentConsumers(2);
    GenericApplicationContext context = new GenericApplicationContext();
    context.getBeanFactory().registerSingleton("foo", queue);
    context.refresh();//w w  w  .j av  a2  s.c  o  m
    container.setApplicationContext(context);
    RabbitAdmin admin = new RabbitAdmin(this.template.getConnectionFactory());
    admin.setApplicationContext(context);
    container.setRabbitAdmin(admin);
    container.afterPropertiesSet();
    container.start();
    for (int i = 0; i < 10; i++) {
        template.convertAndSend(queue.getName(), i + "foo");
    }
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    container.stop();
    container.start();
    latch = new CountDownLatch(10);
    container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch)));
    for (int i = 0; i < 10; i++) {
        template.convertAndSend(queue.getName(), i + "foo");
    }
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    container.stop();
}

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 {//from w  w w .j a  v a 2  s  .  c om
        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.SimpleMessageListenerContainerLongTests.java

@Test
public void testAddQueuesAndStartInCycle() throws Exception {
    final SingleConnectionFactory connectionFactory = new SingleConnectionFactory("localhost");
    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setMessageListener((MessageListener) message -> {
    });/*from  w w w .ja v  a  2s  . c  o  m*/
    container.setConcurrentConsumers(2);
    container.afterPropertiesSet();

    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    for (int i = 0; i < 20; i++) {
        AnonymousQueue anonymousQueue = new AnonymousQueue();
        admin.declareQueue(anonymousQueue);
        container.addQueueNames(anonymousQueue.getName());
        if (!container.isRunning()) {
            container.start();
        }
    }

    int n = 0;
    while (n++ < 100 && container.getActiveConsumerCount() != 2) {
        Thread.sleep(100);
    }
    assertEquals(2, container.getActiveConsumerCount());
    container.stop();
    connectionFactory.destroy();
}

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

@SuppressWarnings("unchecked")
@Test//from  ww  w.  ja v a 2  s .c o  m
public void testWithConnectionPerListenerThread() throws Exception {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class);
    com.rabbitmq.client.Connection mockConnection2 = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection1).thenReturn(mockConnection2).thenReturn(null);
    when(mockConnection1.createChannel()).thenReturn(mockChannel1).thenReturn(null);
    when(mockConnection2.createChannel()).thenReturn(mockChannel2).thenReturn(null);
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockConnection1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);
    when(mockConnection2.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setCacheMode(CacheMode.CONNECTION);

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf);
    container.setConcurrentConsumers(2);
    container.setQueueNames("foo");
    container.afterPropertiesSet();

    CountDownLatch latch1 = new CountDownLatch(2);
    CountDownLatch latch2 = new CountDownLatch(2);
    doAnswer(messageToConsumer(mockChannel1, container, false, latch1)).when(mockChannel1).basicConsume(
            anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class));
    doAnswer(messageToConsumer(mockChannel2, container, false, latch1)).when(mockChannel2).basicConsume(
            anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(), any(Consumer.class));
    doAnswer(messageToConsumer(mockChannel1, container, true, latch2)).when(mockChannel1)
            .basicCancel(anyString());
    doAnswer(messageToConsumer(mockChannel2, container, true, latch2)).when(mockChannel2)
            .basicCancel(anyString());

    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    Set<?> consumers = TestUtils.getPropertyValue(container, "consumers", Map.class).keySet();
    container.stop();
    assertTrue(latch2.await(10, TimeUnit.SECONDS));

    waitForConsumersToStop(consumers);
    Set<?> allocatedConnections = TestUtils.getPropertyValue(ccf, "allocatedConnections", Set.class);
    assertEquals(2, allocatedConnections.size());
    assertEquals("1", ccf.getCacheProperties().get("openConnections"));
}

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

@Test
public void testContainerNotRecoveredAfterExhaustingRecoveryBackOff() throws Exception {
    SimpleMessageListenerContainer container = spy(
            new SimpleMessageListenerContainer(mock(ConnectionFactory.class)));
    container.setQueueNames("foo");
    container.setRecoveryBackOff(new FixedBackOff(100, 3));
    container.setConcurrentConsumers(3);
    doAnswer(invocation -> {//from   w  w  w. ja  va  2 s .  co  m
        BlockingQueueConsumer consumer = spy((BlockingQueueConsumer) invocation.callRealMethod());
        doThrow(RuntimeException.class).when(consumer).start();
        return consumer;
    }).when(container).createBlockingQueueConsumer();
    container.afterPropertiesSet();
    container.start();

    // Since backOff exhausting makes listenerContainer as invalid (calls stop()),
    // it is enough to check the listenerContainer activity
    int n = 0;
    while (container.isActive() && n++ < 100) {
        Thread.sleep(100);
    }
    assertThat(n, lessThanOrEqualTo(100));
}

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);//w  w  w .j a v a 2  s.  co 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.integration.x.rabbit.RabbitChannelRegistry.java

@Override
public void createInbound(final String name, MessageChannel moduleInputChannel,
        final Collection<MediaType> acceptedMediaTypes, boolean aliasHint) {
    if (logger.isInfoEnabled()) {
        logger.info("declaring queue for inbound: " + name);
    }// www . j a  v  a 2s  .c o  m
    this.rabbitAdmin.declareQueue(new Queue(name));
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    if (this.concurrentConsumers != null) {
        listenerContainer.setConcurrentConsumers(this.concurrentConsumers);
    }
    listenerContainer.setQueueNames(name);
    listenerContainer.afterPropertiesSet();
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    DirectChannel bridgeToModuleChannel = new DirectChannel();
    bridgeToModuleChannel.setBeanName(name + ".bridge");
    adapter.setOutputChannel(bridgeToModuleChannel);
    adapter.setHeaderMapper(this.mapper);
    adapter.setBeanName("inbound." + name);
    adapter.afterPropertiesSet();
    this.lifecycleBeans.add(adapter);
    ReceivingHandler convertingBridge = new ReceivingHandler(acceptedMediaTypes);
    convertingBridge.setOutputChannel(moduleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToModuleChannel.subscribe(convertingBridge);
    adapter.start();
}

From source file:org.springframework.integration.x.rabbit.RabbitChannelRegistry.java

@Override
public void tap(String tapModule, final String name, MessageChannel tapModuleInputChannel) {
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    if (this.concurrentConsumers != null) {
        listenerContainer.setConcurrentConsumers(this.concurrentConsumers);
    }/*  w  w w  .j  a  v  a2s .  c o m*/
    Queue queue = this.rabbitAdmin.declareQueue();
    Binding binding = BindingBuilder.bind(queue).to(new FanoutExchange("tap." + name));
    this.rabbitAdmin.declareBinding(binding);
    listenerContainer.setQueues(queue);
    listenerContainer.afterPropertiesSet();
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    DirectChannel bridgeToTapChannel = new DirectChannel();
    bridgeToTapChannel.setBeanName(tapModule + ".bridge");
    adapter.setOutputChannel(bridgeToTapChannel);
    adapter.setHeaderMapper(this.mapper);
    adapter.setBeanName("tap." + name);
    adapter.setComponentName(tapModule + "." + "tapAdapter");
    adapter.afterPropertiesSet();
    this.lifecycleBeans.add(adapter);
    // TODO: media types need to be passed in by Tap.
    Collection<MediaType> acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    ReceivingHandler convertingBridge = new ReceivingHandler(acceptedMediaTypes);
    convertingBridge.setOutputChannel(tapModuleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToTapChannel.subscribe(convertingBridge);
    adapter.start();
}

From source file:org.springframework.integration.x.rabbit.RabbitMessageBus.java

private void doRegisterConsumer(String name, MessageChannel moduleInputChannel, Queue queue) {
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    if (this.concurrentConsumers != null) {
        listenerContainer.setConcurrentConsumers(this.concurrentConsumers);
    }/*from   w w w.j a v a 2  s  .c o m*/
    listenerContainer.setQueues(queue);
    Advice advice = new StatelessRetryOperationsInterceptorFactoryBean().getObject();
    listenerContainer.setAdviceChain(new Advice[] { advice });
    listenerContainer.afterPropertiesSet();
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    DirectChannel bridgeToModuleChannel = new DirectChannel();
    bridgeToModuleChannel.setBeanName(name + ".bridge");
    adapter.setOutputChannel(bridgeToModuleChannel);
    adapter.setHeaderMapper(this.mapper);
    adapter.setBeanName("inbound." + name);
    adapter.afterPropertiesSet();
    addBinding(Binding.forConsumer(adapter, moduleInputChannel));
    ReceivingHandler convertingBridge = new ReceivingHandler();
    convertingBridge.setOutputChannel(moduleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToModuleChannel.subscribe(convertingBridge);
    adapter.start();
}

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 {// ww w  .  java 2 s.  c  om
        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);
    }
}