djxak djxak - 6 months ago 105
Java Question

Is it possible to set prefetch count on @RabbitListener

I know it is possible to make

SimpleMessageListenerContainer
bean and set prefetch count and message listener here, like this:

@Bean
public SimpleMessageListenerContainer messageListenerContainer(
ConnectionFactory rabbitConnectionFactory,
Receiver receiver) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory);
container.setQueueNames("hello");
container.setMessageListener(new MessageListenerAdapter(receiver, "receive"));
container.setPrefetchCount(1000);
return container;
}


But how to set prefetch count for channel if I want to use declarative approach using
@RabbitListener
?

@Component
public class Receiver {

private static final Logger log = LoggerFactory.getLogger(Receiver.class);

@RabbitListener(queues = "hello") // how to set prefetch count here?
public void receive(String message) {
log.info(" [x] Received '{}'.", message);
}

}


It is not possible?

Answer

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.