简体   繁体   English

春天-等待Rabbitmq消息监听器完成

[英]Spring - wait for rabbitmq message listener to complete

I have two message listeners, each listening to it's own message queue on same RabbitMQ server. 我有两个消息侦听器,每个侦听器都在同一RabbitMQ服务器上侦听自己的消息队列。

Now, when first listener receives a message on its queue, it has to ask other listener if he has any messages to process in it's queue, and in case he has, wait for this messages to be processed by second listener prior continuing with it's own execution. 现在,当第一个侦听器在其队列中接收到一条消息时,它必须询问其他侦听器是否在其队列中有任何消息要处理,并且如果有,请等待第二个侦听器处理此消息,然后再继续自己的消息执行。

I would need something like this: 我需要这样的东西:

SimpleMessageListenerContainer first;
SimpleMessageListenerContainer second;
if(second.hasReceivedMessageButItsStillNotProcessed){
  Thread.waitUntilSecondProcessesAMessage();
}

or like this 或像这样

while(rabbitAdmin.getQueueProperties("qName").get("UNACKED_MSG_COUNT")>0){
  Thread.waitUntilSecondProcessesAMessage();
}

Any help appreciated. 任何帮助表示赞赏。

If you are using spring, you can use this Queue Size in Spring AMQP Java client (second answer) to get the queue message size. 如果您使用的是Spring,则可以在Spring AMQP Java客户端 (第二个答案)中使用此队列大小来获取队列消息大小。 You could try something like this: 您可以尝试这样的事情:

Spring queues config: Spring队列配置:

<jms:listener-container 
    connection-factory="jmsFactory"  
    destination-type="queue1">
        <jms:listener destination="queue1" ref="consumer1" method="consume"/>
</jms:listener-container>
<bean id="consumer1" class="m.p.e.MessageConsumer1" scope="tenant"/>
<jms:listener-container 
    connection-factory="jmsFactory"  
    destination-type="queue2" >
        <jms:listener destination="queue2" ref="consumer2" method="consume"/>
</jms:listener-container>
<bean id="consumer2" class="m.p.e.MessageConsumer2" scope="tenant"/>

Your StatsCounter as Queue Size in Spring AMQP Java client (second answer) : Spring AMQP Java客户端中的 StatsCounter作为队列大小 (第二个答案)

public class QueueStatsProcessor {
    @Autowired
    private RabbitAdmin admin;
    @Autowired
    private List<Queue> rabbitQueues;

    public Integer getCounts(String queueName){
        //find your queue from rabbitQueues
        //return the 
        props = admin.getQueueProperties(queue.getName());
        return Integer.parseInt(props.get("QUEUE_MESSAGE_COUNT");        
    }
}

And your second consumer that must wait until there is no messages on queue1 : 您的第二个使用者必须等待,直到queue1上没有消息queue1

public class MessageConsumer2{
@Autowired
QueueStatsProcessor queueStatesProcesor;

public void consume(){
    while(queueStatesProcesor.getCounts("queue1")  > 0){
        Thread.sleep(1000);
    }
    //do your own work
}

}

I think this logic is a little complex to manage it "manually", I recommend you to use something like Spring Integration or Apache Camel . 我认为这种逻辑“手动”管理起来有点复杂,我建议您使用诸如Spring IntegrationApache Camel之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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