【问题标题】:How to receive messages for a correlationid from RabbitMQ using Spring AMQP如何使用 Spring AMQP 从 RabbitMQ 接收相关 ID 的消息
【发布时间】:2014-07-08 11:09:34
【问题描述】:

我浏览了 RabbitTemplate 的 API。它只提供从队列中获取消息的接收方法。但是,无法获取具有特定相关 ID 的消息。你能帮我理解我在这里缺少什么吗?

目前,我正在使用来自 ActiveMQ 的 JMS API 来使用以下代码接收消息,该代码使用消息选择器创建消费者。希望对带有 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;
} 

【问题讨论】:

    标签: rabbitmq amqp spring-amqp


    【解决方案1】:

    您在 JMS 中使用 messageSelector 字符串; RabbitMQ/AMQP 没有等价物。

    相反,每个消费者都有自己的队列,您使用代理中的直接或主题交换来进行路由。我建议你看看the tutorials on the rabbitmq web sitetopics

    如果您使用correlationId 进行请求/回复处理,请考虑使用模板中的内置sendAndReceiveconvertSendAndReceive 方法。请参阅reference documentation 了解更多信息。

    【讨论】:

    • 非常感谢加里
    • 可以设置convertSendAndReceive返回的超时时间吗?如果超时,convertSendAndReceive 应该返回某种异常。
    • 默认超时时间为5秒,用setReplyTimeout(long)(毫秒)调整。如果超时,您将得到一个空返回值,而不是异常。
    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多