2014-05-20 90 views
1

我經歷了RabbitTemplate的API。它只提供從隊列中獲取消息的接收方法。但是,無法通過特定的相關ID獲取消息。你能幫我理解我在這裏錯過了什麼嗎?如何使用Spring AMQP接收來自RabbitMQ的correlationid消息

目前,我使用ActiveMQ的JMS API來使用以下代碼來接收消息,其中createConsumer帶有消息選擇器。展望與RabbitMQ的做同樣的使用Spring AMQP:

private ObjectMessage receiveMessage(final String readQueue, final UUID correlationId, final boolean isBroadcastMessage, final int readTimeout) throws JMSException 
{ 
    final ActiveMQConnectionFactory connectionFactory = this.findConnectionFactory(readQueue); 
    Connection connection = null; 
    Session session = null; 
    MessageConsumer consumer = null; 
    ObjectMessage responseMessage = null; 

    try 
    { 
     connection = connectionFactory.createConnection(); 
     connection.start(); 
     session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 

     Destination destination = session.createQueue(readQueue); 

     consumer = session.createConsumer(destination, "correlationId = '" + correlationId + "'"); 
     final Message message = consumer.receive(readTimeout); 
    } 
    finally 
    { 
     if (consumer != null) 
     { 
      consumer.close(); 
     } 
     if (session != null) 
     { 
      session.close(); 
     } 
     if (connection != null) 
     { 
      connection.close(); 
     } 
    } 
    return responseMessage; 
} 

回答

1

您正在使用JMS一個messageSelector串; RabbitMQ/AMQP沒有等同物。

相反,每個消費者都有自己的隊列,並且在代理中使用直接或主題交換來執行路由。我建議你看看the tutorials on the rabbitmq web sitetopics

如果您正在使用correlationId進行請求/回覆處理,請考慮在模板中使用內置的sendAndReceiveconvertSendAndReceive方法。有關更多信息,請參閱reference documentation

+0

非常感謝Gary – GRaj

+0

我們可以設置convertSendAndReceive返回的超時時間嗎?如果超出超時時間,convertSendAndReceive應該返回某種異常。 – GRaj

+0

默認的超時時間是5秒,用'setReplyTimeout(long)'(毫秒)來調整它。如果超時,你會得到一個空返回值,而不是一個例外。 –

相關問題