我通过 SpringJMS 在我的项目中使用 MQ,作为代理我使用 ActiveMQ。
我需要根据消息设置 expiration,所以我尝试使用 message.setJMSExpiration
但没有成功。所有到达 ActiveMQ 的消息都有 expiration=0。
有人成功地使用 Spring 为每条消息设置了过期时间吗?
为了配置 JmsTemplate,我使用了默认值 explicitQosEnabled = false;
所以我希望我的 Message 属性不会过期。但正如我在 ActiveMQSession.class 中看到的,此消息属性将被覆盖:
long expiration = 0L;
if (!producer.getDisableMessageTimestamp()) {
long timeStamp = System.currentTimeMillis();
message.setJMSTimestamp(timeStamp);
if (timeToLive > 0) {
expiration = timeToLive + timeStamp;
}
}
message.setJMSExpiration(expiration);
//me: timeToLive coming from default values of Producer/JmsTemplate...
我做错了什么?或者使用此工具根本不可能。
最佳答案
我不知道为什么 Spring 决定排除这个,但你可以扩展 JmsTemplate 并重载一些方法,传递一个 timeToLive 参数。
public class MyJmsTemplate extends JmsTemplate {
public void send(final Destination destination,
final MessageCreator messageCreator, final long timeToLive)
throws JmsException {
execute(new SessionCallback<Object>() {
public Object doInJms(Session session) throws JMSException {
doSend(session, destination, messageCreator, timeToLive);
return null;
}
}, false);
}
protected void doSend(Session session, Destination destination,
MessageCreator messageCreator, long timeToLive) throws JMSException {
Assert.notNull(messageCreator, "MessageCreator must not be null");
MessageProducer producer = createProducer(session, destination);
try {
Message message = messageCreator.createMessage(session);
if (logger.isDebugEnabled()) {
logger.debug("Sending created message: " + message);
}
doSend(producer, message, timeToLive);
// Check commit - avoid commit call within a JTA transaction.
if (session.getTransacted() && isSessionLocallyTransacted(session)) {
// Transacted session created by this template -> commit.
JmsUtils.commitIfNecessary(session);
}
} finally {
JmsUtils.closeMessageProducer(producer);
}
}
protected void doSend(MessageProducer producer, Message message,
long timeToLive) throws JMSException {
if (isExplicitQosEnabled() && timeToLive > 0) {
producer.send(message, getDeliveryMode(), getPriority(), timeToLive);
} else {
producer.send(message);
}
}
}
关于java - 使用 SpringJMS 设置每条消息的过期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36887230/