Is it possible to set prefetch count on @RabbitListener
Solution according to @artem-bilan answer:
Declare RabbitListenerContainerFactory
bean with prefetch count 10 in some @Configuration
class:
@Bean
public RabbitListenerContainerFactory<SimpleMessageListenerContainer> prefetchTenRabbitListenerContainerFactory(ConnectionFactory rabbitConnectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(rabbitConnectionFactory);
factory.setPrefetchCount(10);
return factory;
}
Receiver
bean uses this factory bean:
@Component
public class Receiver {
private static final Logger log = LoggerFactory.getLogger(Receiver.class);
@RabbitListener(queues = "hello", containerFactory = "prefetchTenRabbitListenerContainerFactory")
public void receive(String message) {
log.info(" [x] Received '{}'.", message);
}
@RabbitListener(queues = "hello")
public void receiveWithoutPrefetch(String message) {
log.info(" [x] Received without prefetch '{}'.", message);
}
}
Two listeners here is just for demo purpose.
With this configuration Spring creates two AMQP channels. One for each @RabbitListener
. First with prefetch count 10 using our new prefetchTenRabbitListenerContainerFactory
bean and second with prefetch count 1 using default rabbitListenerContainerFactory
bean.
The @RabbitListener
has containerFactory
option:
/**
* The bean name of the {@link org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory}
* to use to create the message listener container responsible to serve this endpoint.
* <p>If not specified, the default container factory is used, if any.
* @return the {@link org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory}
* bean name.
*/
String containerFactory() default "";
Where you can configure SimpleRabbitListenerContainerFactory
with the desired prefetchCount
and the target SimpleMessageListenerContainer
for that annotation will have that option for you.