Published on

Java Messaging Service Basics

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Way to Java Messaging
  2. 2. Messaging Messaging is a method of communication betweensoftware components or applications. Each client connects to a messaging agent thatprovides facilities for creating, sending, receiving, andreading messages. Messaging enables distributed communication that isloosely coupled such that regardless of the availabilityof the sender and the receiver at the same time theystill could communicate.
  3. 3. JMS API The Java Message Service is a Java API allowing theapplications to create, send, receive, and readmessages. Asynchronous. A JMS provider can deliver messagesto a client as they arrive; a client does not have torequest messages in order to receive them. Reliable. The JMS API can ensure that a message isdelivered once and only once.
  4. 4. Advantages of JMS API Allows components to not depend on informationabout other components interfaces, making them easyto replace. Allows application to run whether or not allcomponents are up and running simultaneously The application business model allows a component tosend information to another and to continue tooperate without receiving an immediate response
  5. 5. JMS API Architecture A JMS application is composed of the following parts. JMS provider is a messaging system that implements the JMSinterfaces and provides administrative and control features. JMS clients are the programs or components, written in Javaprogramming language, that produce and consume messages. Messages are the objects that communicate informationbetween JMS clients. Administered objects are preconfigured JMS objects created byan administrator for the use of clients. The two kinds ofadministered objects are destinations and connection factories. Native clients are programs that use a messaging productsnative client API instead of the JMS API. An application firstcreated before the JMS API became available and subsequentlymodified is likely to include both JMS and native clients.
  6. 6. JMS API Architecture
  7. 7. JMS API Architecture Administrative tools allow to bind destinations andconnection factories into a Java Naming and DirectoryInterface(JNDI) API namespace. A JMS client can then look up the administered objectsin the namespace and then establish a logicalconnection to the same objects through the JMSprovider.
  8. 8. Point-to-Point Messaging Domain A point-to-point (PTP) product or application is builtaround the concept of message queues, senders, andreceivers. Each message is addressed to a specific queue, andreceiving clients extract messages from the queue(s)established to hold their messages. Queues retain all messages sent to them until themessages are consumed or until the messages expire.
  9. 9. Point-to-Point Messaging
  10. 10. Point-to-Point Messaging Each message has only one consumer. A sender and a receiver of a message have no timingdependencies. The receiver can fetch the messagewhether or not it was running when the client sent themessage. The receiver acknowledges the successful processing ofa message. PTP messaging is used when every message send mustbe processed successfully by a single consumer.
  11. 11. Publish/Subscribe MessagingDomain In a publish/subscribe product or application, clientsaddress messages to a topic. Publishers and subscribers are generally anonymousand may dynamically publish or subscribe to thecontent hierarchy. The system takes care of distributing the messagesarriving from a topics multiple publishers to itsmultiple subscribers. Topics retain messages only as long as it takes todistribute them to current subscribers.
  12. 12. Publish/Subscribe Messaging
  13. 13. Pub / Sub Messaging Characteristics Each message may have multiple consumers. Publishers and subscribers have a timing dependency.A client that subscribes to a topic can consume onlymessages published after the client has created asubscription, and the subscriber must continue to beactive in order for it to consume messages. Durable subscriptions can receive messages sentwhile the subscribers are not active, relaxing thetiming dependency to some extent and provide theflexibility and reliability of queues but still allowclients to send messages to many recipients
  14. 14. Message Consumption Messaging products are inherently asynchronous such that nofundamental timing dependency exists between the productionand the consumption of a message. Messages can be consumed in either of two ways: Synchronously. A subscriber or a receiver explicitly fetches themessage from the destination by calling the receive method. Thereceive method can block until a message arrives or can time outif a message does not arrive within a specified time limit. Asynchronously. A client can register a message listener with aconsumer. A message listener is similar to an event listener.Whenever a message arrives at the destination, the JMS providerdelivers the message by calling the listeners onMessage method,which acts on the contents of the message.
  15. 15. JMS API Programming Model The basic building blocks of a JMS application consistof Administered Objects: connection factories anddestinations connections. Sessions Message producers Message consumers Message
  16. 16. JMS API Programming Model
  17. 17. Administered Objects The Destinations and Connection factories are bestmaintained administratively rather thanprogrammatically. JMS clients access these objects through interfaces thatare portable, so a client application can run with littleor no change on more than one implementation of theJMS API. Ordinarily, an administrator configures administeredobjects in a JNDI API namespace, and JMS clients thenlook them up, using the JNDI API.
  18. 18. Connection Factories A connection factory is the object a client uses tocreate a connection with a provider. A connection factory encapsulates a set of connectionconfiguration parameters that has been defined by anadministrator. A pair of connection factories come preconfiguredwith the J2EE SDK and are accessible as soon as youstart the service. Each connection factory is an instance of either theQueueConnectionFactory or theTopicConnectionFactory interface.
  19. 19. Connection Factories New connection factories can be created by using the followingcommands: j2eeadmin -addJmsFactory jndi_name queue j2eeadmin -addJmsFactory jndi_name topic A JNDI API lookup of the connection factory is as follows: Context ctx = new InitialContext(); QueueConnectionFactory queueConnectionFactory =(QueueConnectionFactory)ctx.lookup("QueueConnectionFactory"); TopicConnectionFactory topicConnectionFactory =(TopicConnectionFactory)ctx.lookup("TopicConnectionFactory"); Calling InitialContext method without parameters results in asearch of the current classpath for a vendor-specific file which indicates the JNDI API implementation touse and the namespace to be used.
  20. 20. Destinations A destination is the object a client uses to specify the targetof messages it produces and the source of messages itconsumes. In the PTP messaging domain, destinations are calledqueues, while in pub/sub messaging domain. Destinationsare called topics. Following J2EE SDK command is used to create them: j2eeadmin -addJmsDestination queue_name queue j2eeadmin -addJmsDestination topic_name topic A JMS application may use multiple queues and/or topics. A JNDI API lookup for topic or queue is as follows: TopicQueue name = (TopicQueue )ctx.lookup("name“);
  21. 21. Connections A connection encapsulates a virtual connection with a JMSprovider. It is an open TCP/IP socket between a client and a providerservice daemon. A connection is used to create one or more sessions. Connections can be created by implementing either theQueueConnection or the TopicConnection interface. Connections should be closed when an application completes torelease the resources by the JMS provider. Closing a connection also closes its sessions and their messageproducers and message consumers. Call the connection’s ‘start’ method to start consumingresources. By calling the ‘stop’ method, the message delivery is stoppedtemporarily without closing the connection.
  22. 22. Sessions A session is a single-threaded context for producing andconsuming messages. Sessions serialize the execution of message listeners andcreates message producers, message consumers, andmessages. A session provides a transactional context with which togroup a set of sends and receives into an atomic unit ofwork. Sessions can be created by implementing either theQueueSession or the TopicSession interface. TopicSession topicSession =topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); The first argument means that the session is nottransacted; the second means that the sessionautomatically acknowledges messages when they havebeen received successfully
  23. 23. Message Producers A message producer is an object created by a session and isused for sending messages to a destination. The PTP form of a message producer implements theQueueSender interface. The pub/sub form implements the TopicPublisherinterface. QueueSession is used to create a sender for the queue, andTopicSession is used to create a publisher for the topic. With a QueueSender, the send method is used while with aTopicPublisher, the publish method is used. An unidentified producer is created by specifying null asthe argument to createSender and createPublisher.
  24. 24. Message Consumers A message consumer is an object created by a sessionand is used for receiving messages sent to adestination. A message consumer allows a JMS client to registerinterest in a destination with a JMS provider. The JMS provider manages the delivery of messagesfrom a destination to the registered consumers of thedestination. The PTP form of message consumer implements theQueueReceiver interface while the pub/sub formimplements the TopicSubscriber interface.
  25. 25. Message Consumers QueueSession is used to create a receiver for the queue while aTopicSession is used to create a subscriber for the topic. QueueReceiver queueReceiver =queueSession.createReceiver(myQueue); queueConnection.start(); Message m = queueReceiver.receive(1000); // timeout Once the message consumer is created, it becomes active. When the close method for a QueueReceiver or aTopicSubscriber is called it makes the message consumerinactive. Message delivery does not begin until the connection is startedby calling the start method. The receive method is used to consume a message synchronouslywith either a QueueReceiver or a TopicSubscriber.
  26. 26. Message Listeners A message listener is an object that acts as anasynchronous event handler for messages. Message Listener object implements theMessageListener interface, which contains theonMessage method which defines the actions to betaken when a message arrives. The message listener is registered with a specificQueueReceiver or TopicSubscriber by using thesetMessageListener method. For example: TopicListener topicListener = new TopicListener();topicSubscriber.setMessageListener(topicListener);
  27. 27. Message Listeners After registering the message listener, the startmethod is called on the QueueConnection or theTopicConnection in order to begin message delivery. If start method is called before registering the messagelistener, messages are likely to be missed. Once message delivery begins, the message consumerautomatically calls the message listeners onMessagemethod, taking the argument of type Message(suitable to cast to any message types) whenever amessage is delivered.
  28. 28. Message Listeners A message listener is not specific to a particular destinationtype i.e. either a queue or a topic. A message listener expects a specific message type andformat. A message listener must either assume a particulardestination type or obtain the destination type of themessage and create a producer for that destination type toreply to messages. onMessage method handles all the exceptions withoutthrowing a RuntimeException. The session used to create the message consumer serializesthe execution of all message listeners registered with thesession. Only one of the session’s message listeners is running atany given time.
  29. 29. Message Selectors JMS API message selector allows the application tofilter the messages it receives, thus allowing a messageconsumer to specify the messages it is interested in. A message selector is a String that contains anexpression. The createReceiver, createSubscriber, andcreateDurableSubscriber methods each have a formthat allowing to specify a message selector as anargument. The message consumer then receives only messageswhose headers and properties match the selector. A message selector cannot select messages on the basisof the content of the message body.
  30. 30. Messages The purpose of a JMS application is to produce and toconsume messages which can be used by othersoftware applications. JMS messages have a basic format that is simple buthighly flexible, allowing to create messages withmatching formats used by non-JMS applications onheterogeneous platforms. A JMS message has three parts: A Header Properties(Optional) A Body (Optional)
  31. 31. Message Headers A JMS message header contains a number ofpredefined fields that contain values that both clientsand providers use to identify and to route messages. Each header field has associated setter and gettermethods, documented in the description of theMessage interface. Some header fields are intended to be set by a client,but many are set automatically by the send or thepublish method, which overrides any client-set values.
  32. 32. Message Properties Message Properties can be created and set for themessages providing additional values other than theheader fields. Message properties are used to provide compatibilitywith other messaging systems, or used to createmessage selectors. The JMS API provides some predefined propertynames that a provider may support.
  33. 33. Message Bodies The JMS API defines five message body formats, calledmessage types, allowing to send and receive data indifferent forms and provide compatibility with existingmessaging formats.
  34. 34. JMS Message TypesMessage Type Body ContainsTextMessage A java.lang.String objectMapMessage A set of name/value pairs, with names as String objects andvalues as primitive types in Java, with the order undefined.BytesMessage A stream of uninterpreted bytes which is an encoding of thebody to match an existing message format.StreamMessage A stream of primitive values in the Java, filled and readsequentially.ObjectMessage A Serializable object in the JavaMessage Nothing. Composed of header fields and properties only.Useful when message body is not required.
  35. 35. Getting JMS to work
  36. 36. Connections and Connection Factories A connection represents a logical connection to theJMS provider. JMS client obtains a connection to the JMS provider . Each JMS provider provides a connection factory toallow JMS client to get a connection. JMS does not standardize the informationencapsulated in the connection factory. There are two types of connection factories: one forpoint−to−point and another forpublish−and−subscribe.
  37. 37. Sessions A "session" is a client’s own private view of theconnection. Each connection may have many sessions inprogress at the same time. As connection is necessary to communicatewith a JMS provider, a session is necessary tocommunicate with the connection. A session is a factory for producing messages aswell.
  38. 38. Destinations All the messages are sent to a destination, messages are receivedfrom a destination as well. No standardization on the information encapsulated in adestination. The destination is obtained by a user of the messaging system,through a session. The type of destination used to send and receive messages dependson the messaging style being used. For point−to−point messaging the destination is called a "queue“. For publish−and−subscribe messaging the destination is called a"topic". A session created for the point−to−point messaging style can onlybe used to get a queue while a session created for thepublish−and−subscribe messaging style can only be used to get atopic.
  39. 39. The Hello World Sender // Get a connection factory for the point−to−point style // i.e. a queue connection factory. QueueConnectionFactory myConnectionFactory = new com.sun.messaging.QueueConnectionFactory(); // Use myConnectionFactory to get a queue connection QueueConnection myConnection = myConnectionFactory.createQueueConnection(); Here the name of any class used with thepoint−to−point messaging style begins with“Queue” while the name of any class used with thepublish−and−subscribe style begins with “Topic”.
  40. 40. The Hello World Sender // Use myConnection to create a queue session QueueSession mySession = myConnection.createQueueSession(false,1); // Use mySession to get the queue Queue myQueue =mySession.createQueue("HelloWorldQueue"); // Create a sender used to send a message QueueSender mySender =mySession.createSender(myQueue); // Create the HelloWorld message TextMessage m = mySession.createTextMessage(); m.setText("Hello World"); // Use mySender to send the message mySender.send(m);
  41. 41. The Hello World Receiver The receiver also requires to obtain a connectionfactory, the connection, the session, and the queueexactly in the same way as the sender. The session is used to create a receiver. The receiver is told which queue to receive messages. // Use mySession to create a receiver QueueReceiver myReceiver =mySession.createReceiver(myQueue); To actually receive a message, the program calls thereceive method as follows: TextMessage m = (TextMessage)myReceiver.receive();
  42. 42. The Hello World Publisher // Get a connection factory for thepublish−and−subscribe style // i.e. a topic connection factory. TopicConnectionFactory myConnectionFactory =new com.sun.messaging.TopicConnectionFactory(); // Use myConnectionFactory to get a Topic connection TopicConnection myConnection =myConnectionFactory.createTopicConnection(); The class names for the connection factory andconnection begin with "Topic."
  43. 43. The Hello World Publisher // Use myConnection to create a Topic session TopicSession mySession =myConnection.createTopicSession(false,1); // Use mySession to get the Topic Topic myTopic =mySession.createTopic("HelloWorldTopic"); // Use mySession to create a publisher for myTopic TopicPublisher myPublisher =mySession.createPublisher(myTopic);
  44. 44. Publishing message using Publish // Create the HelloWorld message TextMessage m = session.createTextMessage(); m.setText("Hello World"); // Use myPublisher to publish the message myPublisher.publish(m);
  45. 45. The Hello World Subscriber The subscriber also requires to obtain a connectionfactory, the connection, the session, and the queuesimilar as the publisher. // Use mySession to create a subscriber TopicSubscriber mySubscriber =mySession.createSubscriber(myTopic); // To receive a message, call the receive method TextMessage m =(TextMessage)mySubscriber.receive();
  46. 46. Administrable objects Standard objects that are created andcustomized by the JMS provider and used byclient software to gain access to the messagingproduct. Both the destination and connection factoryare examples of administrable objects. JMS providers should make the administeredobjects available in a JNDI namespace.
  47. 47. Destination Interface JMS defines a Destination object, in order toencapsulate all of the provider specificaddressing information. The Destination interface is a "marker"interface i.e. it is used to identify a validdestination object The Queue (or TemporaryQueue) and theTopic (or TemporaryTopic) interfaces arederived from the Destination interface.
  48. 48. Connection factory Interface JMS defines the connection factoryadministrable object that encapsulates allthe provider specific connectioninformation. Connection factory is a "marker" interface. The QueueConnectionFactory or theTopicConnectionFactory interfaces, arederived from Connection Factory interface.
  49. 49. Connection Interface public interface Connection { String getClientID() throws JMSException; void setClientID(String clientID) throws JMSException; ConnectionMetaData getMetaData() throws JMSException; ExceptionListener getExceptionListener() throws JMSException; void setExceptionListener(ExceptionListener listener) throws JMSException; void start() throws JMSException; void stop() throws JMSException; void close() throws JMSException; }
  50. 50. Connection Interface When the client gets an actual connection tothe JMS using a connection factory, it getsthe connection in the form of a connectionobject The QueueConnection and theTopicConnection interfaces are derived fromthe Connection interface.
  51. 51. Connection Interface The setExceptionListener method on the connectionobject enables to pass an object that implements theExceptionListener interface, allowing the connection toasynchronously notify by calling the onException methodin case of exception. Connection MetaData which provides details such asversion, product name and JMS properties, can be accessedby calling getMetaData method on the Connectioninterface. The start method of the Connection interface is called tobegin the message arrival at the connection’s consumers.
  52. 52. Session Interface public interface Session extends Runnable { static final int AUTO_ACKNOWLEDGE = 1; static final int CLIENT_ACKNOWLEDGE = 2; static final int DUPS_OK_ACKNOWLEDGE = 3; BytesMessage createBytesMessage() throws JMSException; MapMessage createMapMessage() throws JMSException; Message createMessage() throws JMSException; ObjectMessage createObjectMessage() throws JMSException; ObjectMessage createObjectMessage(Serializable object) throws JMSException; StreamMessage createStreamMessage() throws JMSException; TextMessage createTextMessage() throws JMSException; TextMessage createTextMessage(String text) throws JMSException; boolean getTransacted() throws JMSException; void commit() throws JMSException; void rollback() throws JMSException; void close() throws JMSException; void recover() throws JMSException; MessageListener getMessageListener() throws JMSException; void setMessageListener(MessageListener listener) throws JMSException; public void run(); }
  53. 53. Session Interface Each message that a JMS provider delivers to aconsumer must be acknowledged. If a message is not acknowledged it may be redeliveredto the consumer by the JMS provider. The session can be configured to automaticallyacknowledge each message as it is received/processed. session = connection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE); Acknowledging one message actually acknowledges allmessages that the session has consumed
  54. 54. Session Interface In a non−transacted session, messages are sent/publishedand received/consumed one at a time, while transactedsessions allow grouping of messages in bunches beforesending or receiving them. The getTransacted method returns a boolean to indicate ifthe session is transacted. The commit and rollback methods are used to commit androllback the session transaction, if the session istransacted. The recover method is used to stop a session and restart it. Session is a factory for creating message senders andreceivers, which are called message producers and messageconsumers respectively
  55. 55. MessageConsumer Interface A message consumer is an object that implements theMessageConsumer interface. public interface MessageConsumer { String getMessageSelector() throws JMSException; MessageListener getMessageListener() throws JMSException; void setMessageListener(MessageListener listener) throws JMSException; Message receive() throws JMSException; Message receive(long timeout) throws JMSException; Message receiveNoWait() throws JMSException; void close() throws JMSException; }
  56. 56. MessageConsumer Interface Message consumer is used by client to receive messages from adestination object. Examples: queue receiver and topic subscriber. A message consumer can be created with or without a messageselector. Message selector allows the client to restrict the messagesdelivered to the message consumer to those that match theselector. A client can request the next message from a message consumerusing one of its receive methods. The client can choose to call the blocking receive method withno parameters, or poll the consumer by calling either the receivemethod with a time out or the receiveNoWait method that doesnot wait at all.
  57. 57. MessageConsumer Interface A client can register a message listener object with a messageconsumer by calling setMessageListener method by passing amessage listener object as a parameter. A message listener is an object that implements theMessageListener interface. The message consumer delivers the messages as they arrive bycalling the message listener’s onMessage method. Registering a message listener allows clients to asynchronouslyreceive messages without having to block/poll the messageconsumer. The close method is used to relinquish the allocated resources. The close method call blocks until any receive method call ormessage listener call in progress has completed.
  58. 58. Message Producers A message producer is an object that implements the MessageProducerinterface. public interface MessageProducer { void setDisableMessageID(boolean value) throws JMSException; boolean getDisableMessageID() throws JMSException; void setDisableMessageTimestamp(boolean value) throws JMSException; boolean getDisableMessageTimestamp() throws JMSException; void setDeliveryMode(int deliveryMode) throws JMSException; int getDeliveryMode() throws JMSException; long getTimeToLive() throws JMSException; void setTimeToLive(long timeToLive) throws JMSException; void setPriority(int defaultPriority) throws JMSException; int getPriority() throws JMSException; void close() throws JMSException; }
  59. 59. Message Producers A message producer can be created without supplying adestination, but a destination must be input on every sendoperation. Each message can be associated with a unique identifier., knownas the message ID, which can be ignored by callingsetDisableMessageID method. Similarly each message can be marked with a timestamp, whichcan be ignored by calling setDisableMessageTimestamp method. Message producer also provides a pair of methods,setDeliveryMode and getDeliveryMode, to set default messagedelivery mode. JMS supports two modes of message delivery: persistent andnon−persistent, depending on whether message is logged to astable storage. Delivery mode is set to persistent by default.
  60. 60. Message Producers The setTimeToLive method allows the client to specifya default time−to−live value in milliseconds, from thetime the message is sent. The default time−to−live is set to zero, which is aspecial value indicating no expiration or unlimited life. The setPriority method allows the client to specify thedefault priority of sent messages, with a priority valueof 0 being the lowest priority and 9 being the highest. Priority is set to 4, by default. QueueSender or the TopicPublisher interface arederived from the MessageProducer interface.
  61. 61. Closing a Session The close method on a session will not return untilnone of its message listeners are running and ifthere are any pending receives, all of them arereturned with either a null or a message. When a session is closed there is no need to closeits constituent message producers and consumers. Closing a transacted session rollbacks all of itstransactions in progress. Once a session has been closed, any attempt to useit or its message consumers and producers throwsan IllegalStateException.