MessageConsumer不消费消息

问题描述 投票:6回答:2

我的应用程序在Jboss 7.1.1上运行。我有一个每分钟运行一次的调度程序,需要检查DLQ中是否有消息并在数据库中进行一些更新。

我写了一个消息,消费者听取预定义的自定义DLQ。问题是,我可以看到自定义DLQ中有消息,但consumer.receiveNoWait()始终返回null。

以下是创建消费者的代码:

/*this is running fine and creating the consumer*/
public DestinationHandlerImpl(ConnectionFactory connectionFactory,
    Destination destination, boolean useTransaction, int delMode,
    boolean isProducer) throws JMSException {
    connection = connectionFactory.createConnection();
    consumer = session.createConsumer(destination);
}

这是使用消息的代码(每隔一分钟运行一次):

/*this always return null, event when there are messages in the queue*/
public <T extends BaseEvent> T recieveMessage()
        throws JMSException {

    Message message = consumer.receiveNoWait(); // ----> always return null!!!

    if (message != null && !(message instanceof ObjectMessage)) {
        throw new IllegalArgumentException(
                "message object has to be of type ObjectMessage");
    }

    // Extract the object from the message
    return message == null ? null : (T) ((ObjectMessage) message).getObject();

}

我已经使用了调试模式,我可以看到消费者目标属性设置为正确的队列,所以我做错了什么?

java java-ee jms jboss7.x message-queue
2个回答
11
投票

找到它,我只需要在开始消费之前添加connection.start()

public <T extends BaseEvent> T recieveMessage()
    throws JMSException {

    connection.start(); // --->**added this line**
    Message message = consumer.receiveNoWait(); 

    if (message != null && !(message instanceof ObjectMessage)) {
        throw new IllegalArgumentException(
            "message object has to be of type ObjectMessage");
    }

    // Extract the object from the message
    return message == null ? null : (T) ((ObjectMessage) message).getObject();
}

2
投票

即使使用connection.start(),我也遇到了这个问题!我的工作解决方案:

使用receive(long timeout)而不是receiveNoWait();

Obs。:1000毫秒,因为在一个简单的测试用例中超时工作正常,但为了确保生产,我用10000毫秒配置它。在我的情况下,在迭代消息时,我在收到null(没有更多消息)时停止,在最后一次调用中,接收(10000)等待整整10秒(显然)。我不得不使用异步方法来缓解性能问题。


编辑:此外,根据实现(jbm),它可能会预取一些消息(预先选择使用),这使得消息不可用,因为它们处于传递状态。

© www.soinside.com 2019 - 2024. All rights reserved.