JMS MessageProducer.setTimeToLive() 与 TextMessage.setJMSExpiration()

JMS MessageProducer.setTimeToLive() vs. TextMessage.setJMSExpiration()

调用 MessageProducer.setTimeToLive() 和调用 TextMessage.setJMSExpiration() 有区别吗?

我可以从文档中看到javax.jms.MessageProducer.setTimeToLive()说它

Sets the default length of time in milliseconds from its dispatch time that a produced message should be retained by the message system.

并且 javax.jms.Message.setJMSExpiration() 表示

Sets the message's expiration value.

这些对我来说听起来是一样的。我应该继续将两者设置为相同的值吗?

有一个关键区别,MessageProducer.setTimeToLive() 为该生产者发送的所有消息设置相同的消息过期时间。另一方面,TextMessage.setJMSExpiration() 以每条消息为基础设置消息过期时间。每条消息设置的过期时间会覆盖 MessageProducer 上设置的过期时间。

JMS 还指定了一种在调用MessageProducer.send 方法时设置消息过期时间的方法。

void send(Message message, int deliveryMode,int priority, long timeToLive)

您可以在 MessageProducerTextMessage 上设置消息过期时间。无需同时设置。

您不应为 Message(或 TextMessage,如您的示例)设置过期设置。来自 Java EE 5 Javadocs 的文本令人困惑,并且在 recent versions:

中得到了改进

This method is for use by JMS providers only to set this field when a message is sent. This message cannot be used by clients to configure the expiration time of the message. This method is public to allow a JMS provider to set this field when sending a message whose implementation is not its own.

这意味着您不应使用 Message#setJMSExpiration() 来设置消息过期时间,因为提供程序将在发送消息时覆盖该值。

您应该改为使用它的 MessageProducer 为所有使用 MessageProducer#setTimeToLive() 的消息设置超时,或者,如果您只想为特定消息设置到期时间,请使用 MessageProducer#send(Message, int, int, long) ] 如沙市的回答所示。只有在这种情况下,"per-message" 设置才会覆盖 MessageProducer 的设置。