2016-04-27 128 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); 
     } 
    } 

} 
相關問題