简体   繁体   English

根据 Spring AMQP 中的消费者数量使用队列

[英]Consuming a queue based on its consumer count in Spring AMQP

I want a queue to be consumed by only one subscriber at a time.我希望一个队列一次只能由一个订阅者使用。 So if one subscriber drops, then another one(s) will have the chance of subscribing.因此,如果一个订阅者掉线,那么另一个订阅者将有机会订阅。

I am looking for the correct way of doing it in Spring AMQP.我正在 Spring AMQP 中寻找正确的方法。 I did this in pure Java, based on the example in RabbitMQ's website.根据 RabbitMQ 网站中的示例,我在纯 Java 中执行此操作。 I passively declare the queue, check its consumer count, if it is 0, then start to consume it.我被动地声明了队列,检查它的消费者数量,如果是0,则开始消费它。

Here's the code.这是代码。

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

I also can check the subscriber count in Spring AMQP this way.我也可以通过这种方式检查 Spring AMQP 中的订阅者数量。 But it is too late, because it already listens to the queue.但为时已晚,因为它已经在听队列了。

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

In a nutshell, I want to consume a queue based on its consumer count.简而言之,我想根据消费者数量来消费一个队列。 I hope I am clear.我希望我很清楚。

Set the exclusive flag on the @RabbitListener ;@RabbitListener上设置exclusive标志; RabbitMQ will only allow one instance to consume. RabbitMQ 将只允许一个实例使用。 The other instance(s) will attempt to listen every 5 seconds (by default).其他实例将尝试每 5 秒侦听一次(默认情况下)。 To increase the interval, set the container factory's recoveryBackOff .要增加间隔,请设置容器工厂的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM