Sunday, 5 August 2018

JMS: JMSExpiration: Set the expiration of the message

JMSExpiration  specifies the expiration time of the message. It is represented in milliseconds.

When a message is sent, the JMS provider calculates its expiration time by adding the time-to-live value specified on the send method to the time the message was sent.

Example
/* Set the message expiration to 1 minute from current time */
java.util.Date date = new java.util.Date();
long currentTimeInMillis = date.getTime();
long expiration = currentTimeInMillis + 60000;
message.setJMSExpiration(expiration);

Above statements set the expiration tim of message to 1 minute.

JMSProducer.java
package com.sample.producer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JMSProducer {
 private static final String JMS_PROVIDER_URL = "tcp://127.0.0.1:5050";
 private static final String QUEUE = "DEMO_QUEUE";

 public static void main(String[] args) throws JMSException {
  ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(JMS_PROVIDER_URL);
  Connection connection = connectionFactory.createConnection();
  connection.start();

  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

  Destination destination = session.createQueue(QUEUE);

  MessageProducer producer = session.createProducer(destination);

  TextMessage message = session.createTextMessage("Hello, this is my first message.");

  /* Set the message expiration to 1 minute from current time */
  java.util.Date date = new java.util.Date();
  System.out.println(date);
  long currentTimeInMillis = date.getTime();
  long expiration = currentTimeInMillis + 60000;
  message.setJMSExpiration(expiration);

  producer.send(message);
  connection.close();

 }
}

Note
a.   When an undelivered message’s expiration time is reached, the message should be destroyed. JMS does not define a notification of message expiration.

b.   Clients should not receive messages that have expired; however, JMS does not guarantee that this will not happen.


c.   If the time-to-live is specified as zero, the message’s JMSExpiration header field is set to zero to indicate that the message does not expire.


Previous                                                 Next                                                 Home

No comments:

Post a Comment