问题描述
鉴于我有ActiveMQ队列,其中已经存在许多消息.
Given I have ActiveMQ queue where many messages are already present.
当我将JmsTemplate
上的接收超时设置为RECEIVE_TIMEOUT_NO_WAIT
时,它等于-1
:
When I set receive timeout on JmsTemplate
to RECEIVE_TIMEOUT_NO_WAIT
which is equal to -1
:
jmsTemplate.setReceiveTimeout(JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
并尝试接收这些消息之一:
and try to receive one of those messages:
Message msg = jmsTemplate.receive(queueName);
然后msg
是null
,但是它不符合JavaDoc的要求:
then msg
is null
, but it should not be according JavaDoc:
/**
* Timeout value indicating that a receive operation should
* check if a message is immediately available without blocking.
*/
public static final long RECEIVE_TIMEOUT_NO_WAIT = -1;
那是为什么?
当我这样做时:
jmsTemplate.setReceiveTimeout(1000);
然后检索邮件.
推荐答案
它与JmsTemplate
完全没有任何关系,因为它只是委派给基础JMS Consumer
对象:
It has absolutely nothing at all to do with the JmsTemplate
since it simply delegates to the underlying JMS Consumer
object:
protected Message receiveFromConsumer(MessageConsumer consumer, long timeout) throws JMSException {
if (timeout > 0) {
return consumer.receive(timeout);
}
else if (timeout < 0) {
return consumer.receiveNoWait();
}
else {
return consumer.receive();
}
}
我会说它的工作完全符合JMS设计师的意图:
I would say it is working exactly as the JMS designers intended:
/** Receives the next message if one is immediately available.
*
* @return the next message produced for this message consumer, or
* null if one is not available
*
* @exception JMSException if the JMS provider fails to receive the next
* message due to some internal error.
*/
Message receiveNoWait() throws JMSException;
换句话说,这是在用例中,如果当前没有消息已经由经纪人发送给使用者,则您绝对绝对不想在任何时候阻塞线程-甚至没有等待网络I/O完成,这正是ActiveMQ实施的方式-启动I/O,但如果该I/O没有立即完成则返回null(如果涉及到网络,则很可能是这种情况)
In other words, it is for use cases where you absolutely don't want to block the thread for any time at all, if there is not currently a message that has already been sent to the consumer by the broker - not even waiting for a network I/O to complete, which is exactly how ActiveMQ has implemented it - initiates an I/O but returns null if that I/O doesn't complete immediately (which is most likely the case if there's a network involved).
这篇关于带有RECEIVE_TIMEOUT_NO_WAIT的JmsTemplate不会从JMS队列中检索消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!