gpt4 book ai didi

java - 是否可以在@RabbitListener 上设置预取计数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:09:42 24 4
gpt4 key购买 nike

我知道可以制作 SimpleMessageListenerContainer bean 并在此处设置预取计数和消息监听器,如下所示:

@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;
}

但是,如果我想使用 @RabbitListener 的声明式方法,如何设置 channel 的预取计数?

@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);
}

}

这不可能吗?

最佳答案

根据@artem-bilan 回答的解决方案:

在某些 @Configuration 类中声明 RabbitListenerContainerFactory 预取计数为 10 的 bean:

@Bean
public RabbitListenerContainerFactory<SimpleMessageListenerContainer> prefetchTenRabbitListenerContainerFactory(ConnectionFactory rabbitConnectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(rabbitConnectionFactory);
factory.setPrefetchCount(10);
return factory;
}

Receiver bean 使用这个工厂 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);
}

}

此处的两个监听器仅用于演示目的。
使用此配置,Spring 创建了两个 AMQP channel 。每个 @RabbitListener 一个。首先使用我们新的 prefetchTenRabbitListenerContainerFactory bean 预取计数 10,第二个使用默认 rabbitListenerContainerFactory bean 预取计数 1。

关于java - 是否可以在@RabbitListener 上设置预取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com