Amazon

Wednesday, September 14, 2016

JMS - General and Important Concepts

Transacted Message in JMS

In a Java SE environment or in the Java EE application client container:
If transacted is set to true then the session will use a local transaction which may subsequently be committed or rolled back by calling the session's commit or rollback methods. The argument acknowledgeMode is ignored.
·         If transacted is set to false then the session will be non-transacted. In this case the argument acknowledgeMode is used to specify how messages received by this session will be acknowledged. The permitted values are Session.CLIENT_ACKNOWLEDGE, Session.AUTO_ACKNOWLEDGE and Session.DUPS_OK_ACKNOWLEDGE. For a definition of the meaning of these acknowledgement modes see the links below.
Modifier and Type
Field and Description
static int
With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns.
static int
With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method.
static int
This acknowledgment mode instructs the session to lazily acknowledge the delivery of messages.
static int
This value may be passed as the argument to the method createSession(int sessionMode) on the Connection object to specify that the session should use a local transaction.

In a Java EE web or EJB container, when there is an active JTA transaction in progress:
Both arguments transacted and acknowledgeMode are ignored. The session will participate in the JTA transaction and will be committed or rolled back when that transaction is committed or rolled back, not by calling the session's commit or rollback methods. Since both arguments are ignored, developers are recommended to use createSession(), which has no arguments, instead of this method.

Interface TopicConnectionFactory

Modifier and Type
Method and Description
Creates a topic connection with the default user identity.
createTopicConnection(String userName, String password)
Creates a topic connection with the specified user identity.
public class FirstClient {
      private Context context = null;
      private TopicConnectionFactory factory = null;
      private TopicConnection connection = null;
      private TopicSession session = null;
      private Topic topic = null;
      private TopicPublisher publisher = null;

      public FirstClient() {
            Properties initialProperties = new Properties();
            initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY,
                                  "org.exolab.jms.jndi.InitialContextFactory");
            initialProperties.put(InitialContext.PROVIDER_URL, "tcp://localhost:3035");
            try {
                  context = new InitialContext(initialProperties);
                  factory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
                  topic = (Topic) context.lookup("topic1");
                  connection = factory.createTopicConnection();
                 
                  session = connection.createTopicSession(false//Transacted
                                                          TopicSession.AUTO_ACKNOWLEDGE);
                  publisher = session.createPublisher(topic);
                  EventMessage eventMessage = new EventMessage(1, "Message from FirstClient");
                  ObjectMessage objectMessage = session.createObjectMessage();
                  objectMessage.setObject(eventMessage);
                  connection.start();
                  publisher.publish(objectMessage);
                  System.out.println(this.getClass().getName()+ " has sent a message : " + eventMessage);
                  session.close();
                  connection.close();
                  context.close();
            } catch (Exception e) {
            }
      }
}

Synchronous Messaging and Asynchronous Messaging

In case of asynchronous consumption, the consumer is implementing the MessageListener interface .So the overridden onMessage() method gets the message. But in case of synchronous consumption, the client is waiting to get the message since we used the receive() method of the consumer.
public interface MessageListener
A MessageListener object is used to receive asynchronously delivered messages.

Each session must ensure that it passes messages serially to the listener. This means that a listener assigned to one or more consumers of the same session can assume that the onMessage method is not called with the next message until the session has completed the last call.
Implement MessageListener Interface for implement Asynchronous Consumer.
Modifier and Type
Method and Description
void
onMessage(Message message)
Passes a message to the listener.


JMS Reliablity Mechanisms-Message persistence in JMS

1)Persistent delivery mode  This is the default  delivery mode. It forces the JMS provider to take extra care to avoid the loss of message in case of failure. Message is persisted in secondary storage. When the provider comes alive again message will be delivered to consumer. This ensures reliable message delivery.
2)Non-Persistent delivery mode– If we specify the delivery mode as non-persistent then the provider is not taking extra effort to persist the message if a provider failure occurs.

By using the setDeliveryMode(int value) method of MessageProducer interface .
DeliveryMode.PERSISTENT =2
DeliveryMode.NON_PERSISTENT=1 .
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

Or Use the overloaded send() or publish() method of MessageProducer interface .The second argument in the method call specifies the delivery mode.
producer.send(message, DeliveryMode.PERSISTENT);

Setting Message Priority Levels in JMS

1.       Priority levels – 0 to 9
2.       Default Priority Level – 4
3.       Messages having highest priority are delivered first.
4.       Setting Message Priority
-By using setPriority(int value) method of MessageProducer interface.            
-By using the overloaded publish() method.The third argument  will be the priority.               
     void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException
                topicPublisher.publish(message, DeliveryMode.NON_PERSISTENT, 3,20000)
message - the message to send
deliveryMode - the delivery mode to use
priority - the priority for this message
timeToLive - the message's lifetime (in milliseconds)

Message Expiry in JMS
By default a message never expires.In some cases message will become obsolete after a particular time period. In such situation it is  desirable to set expiration time . After the message expires, it will not be delivered.
We can set the expiration time in program in two ways.
 
Using setTimeToLive() method of MessageProducer interface to set the expiry time of messages from that producer.
Example: topPublisher .setTimeToLive(10000)
The above statement sets the expiry time 10000 milliseconds(10 seconds)
 
Using the overridden method publish() of MessageProducer
Example :topPublisher.publish(message, DeliveryMode.PERSISTENT, 3,10000)
The fourth argument gives the expiry time as 10000 milliseconds
The reliability mechanisms we discussed so far are :
 
Creating Durable Subscriptions in JMS

This ensures message delivery to Subscriber, when it comes alive.
 
topic = (Topic) context.lookup("topic1");
connection = factory.createTopicConnection();
session = connection.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE);
subscriber = session.createDurableSubscriber(topic,"sampleSubscription");
// subscriber = session.createSubscriber(topic);
connection.start();
Message message = subscriber.receive();
A durable subscriber can have only one active subscriber at a time.
A  durable subscriber registers a durable subscription with a unique identity (“sampleSubscriptionin above example). Subsequent subscribers with the same identity will resume the subscription in the state where the previous subscriber was left.
If there is no active subscriber, then the JMS provider keeps the messages till they are received by any subscriber or till the message expires.
 
 




No comments:

Post a Comment

Amazon Best Sellors

Weblogic - Server Creation - Issues

Datasource creation using python script.  Python Script was failing after creating Datasource. From UI Admin Console, if I try to activat...