[英]How to get the consumer count of an already declared queue in Spring-AMQP?
[英]Consuming a queue based on its consumer count in Spring AMQP
我希望一个队列一次只能由一个订阅者使用。 因此,如果一个订阅者掉线,那么另一个订阅者将有机会订阅。
我正在 Spring AMQP 中寻找正确的方法。 根据 RabbitMQ 网站中的示例,我在纯 Java 中执行此操作。 我被动地声明了队列,检查它的消费者数量,如果是0,则开始消费它。
这是代码。
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
int count = channel.queueDeclarePassive(QUEUE_NAME).getConsumerCount();
System.out.println("count is "+count);
if (count == 0) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
} else{
System.out.println("subscribed by some other processor(s)");
}
我也可以通过这种方式检查 Spring AMQP 中的订阅者数量。 但为时已晚,因为它已经在听队列了。
@RabbitListener(queues = "q1")
public void receivedMessageQ1(String message, Channel channel){
try {
int q1 = channel.queueDeclarePassive("q1").getConsumerCount();
// do something.
} catch (IOException e) {
System.out.println("exception occurred");
}
}
简而言之,我想根据消费者数量来消费一个队列。 我希望我很清楚。
在@RabbitListener
上设置exclusive
标志; RabbitMQ 将只允许一个实例使用。 其他实例将尝试每 5 秒侦听一次(默认情况下)。 要增加间隔,请设置容器工厂的recoveryBackOff
。
@SpringBootApplication
public class So56319999Application {
public static void main(String[] args) {
SpringApplication.run(So56319999Application.class, args);
}
@RabbitListener(queues = "so56319999", exclusive = true)
public void listen (String in) {
}
@Bean
public Queue queue() {
return new Queue("so56319999");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.