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

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

Introduction

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

Prototype

public void setPrefetchCount(int prefetchCount) 

Source Link

Document

Tell the broker how many messages to send to each consumer in a single request.

Usage

From source file:crawler.configuration.rabbitmq.RabbitMQConfiguration.java

@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(htmlQueue().getName());
    container.setMessageListener(this);
    container.setConcurrentConsumers(rabbitMQConfigurationProperties.getConcurrentConsumers());
    // container.setMaxConcurrentConsumers(32);
    container.setPrefetchCount(rabbitMQConfigurationProperties.getPrefetchCount());
    // rabbitListenerContainerFactory.setConcurrentConsumers(16);
    return container;
}

From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java

@Test
public void testDebatchByContainerPerformance() throws Exception {
    final List<Message> received = new ArrayList<Message>();
    int count = 100000;
    final CountDownLatch latch = new CountDownLatch(count);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory);
    container.setQueueNames(ROUTE);//from  ww w . java  2s. c o m
    container.setMessageListener((MessageListener) message -> {
        received.add(message);
        latch.countDown();
    });
    container.setReceiveTimeout(100);
    container.setPrefetchCount(1000);
    container.setTxSize(1000);
    container.afterPropertiesSet();
    container.start();
    try {
        BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(1000, Integer.MAX_VALUE, 30000);
        BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler);
        //         RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(this.connectionFactory);
        MessageProperties props = new MessageProperties();
        props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        Message message = new Message(new byte[256], props);
        StopWatch watch = new StopWatch();
        watch.start();
        for (int i = 0; i < count; i++) {
            template.send("", ROUTE, message);
        }
        assertTrue(latch.await(60, TimeUnit.SECONDS));
        watch.stop();
        // System .out .println(watch.getTotalTimeMillis());
        assertEquals(count, received.size());
    } finally {
        container.stop();
    }
}

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  ww.  ja  v a  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.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 ava 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);
    }
}