2016-04-27 127 views
0

我通过SpringJMS在我的项目中使用MQ,作为使用ActiveMQ的代理。 我需要设置到期基于消息,所以我试图用message.setJMSExpiration但没有成功。所有发送给ActiveMQ的消息都有到期= 0使用SpringJMS设置每条消息的过期

有没有人成功使用Spring设置每个消息的过期时间?

对于配置JmsTemplate我使用默认值explicitQosEnabled = false;,所以我期望从我的消息道具到期。但正如我在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... 

我在做什么错了?或者使用这些工具是不可能的。

回答

0

JMSExpiration不是设置过期的方式。请参阅javadoc for Message ...

JMS提供程序在发送消息时设置此字段。此方法可用于更改已收到消息的值。

换句话说,它在发送时被忽略 - 生存时间在producer.send()方法上设置。

过期消息集explicitQosEnabledtruesetTimeToLive(...)

+0

谢谢,我错过了这一点,我可以设置'explicitQosEnabled'到TRUE;,但在参数TTL,producer.send()函数通过JmsTemplate的不适用于我。 – iMysak

+0

不,你在模板上设置TTL;那么当明确的QOS被启用时,模板将在发送时设置TTL。 [见这里](https://github.com/spring-projects/spring-framework/blob/master/spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java#L622)。 –

+0

是的,这是非常清楚的,但在这种情况下,我不能使用不同的过期不同的消息,因为我需要。我无法在并发模式下使用它。 – iMysak

1

我不知道为什么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); 
     } 
    } 

} 
相关问题