1 / 47

JMS (Java Messaging Service)

JMS (Java Messaging Service). Application. Application. Messaging Middleware. Application. Application. Motivation. Performance Reliability Support for multiple senders & receivers. RMI. Messaging :. Messaging. Method of communication between software components or applications.

kosey
Télécharger la présentation

JMS (Java Messaging Service)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JMS(Java Messaging Service) JMS

  2. Application Application Messaging Middleware Application Application Motivation • Performance • Reliability • Support for multiple senders & receivers. RMI Messaging : JMS

  3. Messaging • Method of communication between software components or applications. • A messaging client can send messages to, and receive messages from, any other client. • Enables distributed communication that is loosely coupled. • A component sends a message to a destination, and the recipient can retrieve the message from the destination. However, the sender and the receiver do not have to be available at the same time in order to communicate. The sender and the receiver need to know only what message format and what destination to use. JMS

  4. JMS Introduction • The JMS provides a standard enterprise messaging service for J2EE applications. • JMS queues messages and can deliver them asynchronously: Messaging need not take place in real time; and messages can be sent and consumed at different times. • The Java Message Service is a Java API that allows applications to create, send, receive, and read messages. JMS

  5. JMS Introduction (cont) • The JMS API enables communication that is not only loosely coupled but also: • Asynchronous. A JMS provider can deliver messages to a client as they arrive; a client does not have to request messages in order to receive them. • Reliable. The JMS API can ensure that a message is delivered once and only once. Lower levels of reliability are available for applications that can afford to miss messages or to receive duplicate messages. JMS

  6. Where we can use JMS? • JMS provides reliable communication between separate processes. Example : An e-commerce application might include a • Web front-end for customer order entry • A warehouse then receives the order, packages the appropriate items, • and forwards the order to the shipping department. Finally, the shipping department sends the package and updates the customer's account records. • JMS provides the communication backbone for workflow applications. JMS

  7. Where we can use JMS?(cont) An enterprise application provider is likely to choose a messaging API over a tightly coupled API, such as Remote Procedure Call (RPC), under the following circumstances. • The provider wants the components not to depend on information about other components' interfaces, so that components can be easily replaced. • The provider wants the application to run whether or not all components are up and running simultaneously. • The application business model allows a component to send information to another and to continue to operate without receiving an immediate response. JMS

  8. JMS Architecture A JMS application is composed of the following parts. • JMS Provider • JMS Clients • Messages • Administered Objects (Connection Factories, Queues) JMS

  9. JMS messaging domains The JMS Specification provides a separate domain for each approach and defines compliance for each domain. A standalone JMS provider may implement one or both domains. A J2EE provider must implement both domains. • Point-to-point • Publish and Subscribe JMS

  10. Producer 1 Queue Consumer 1 Producer 2 JMS messaging domains Point to Point Publisher - Subscriber Producer 1 Consumer 1 Topic Producer 2 Consumer 2 JMS

  11. Point-to-Point Point-to-Point • Each message has only one consumer. • A sender and a receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sent the message. • The receiver acknowledges the successful processing of a message. Use PTP messaging when every message you send must be processed successfully by one consumer JMS

  12. Point-to-Point Messaging Point-to-Point Messaging JMS

  13. Publish and subscribe Publish and Subscribe • Each message may have multiple consumers. • Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages. JMS

  14. Publish and subscribe (cont) Publish/Subscribe Messaging JMS

  15. Durable subscribers PERSISTENT message Producer Durable Subscriber1 (connected) Message Server Durable Subscriber2 (not connected) Persistent store Undelivered messages delivered to Subscriber2 when reconnected JMS

  16. Message Consumption Messages can be consumed in either of two ways: • Synchronously. A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit. • Asynchronously. A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener's onMessage() method, which acts on the contents of the message. JMS

  17. The JMS API Programming Model JMS

  18. The JMS API Programming Model The way to operate within the JMS framework is as follows: • Get the JNDI initial context. • Look up a connection factory (for the right type of destination, topic or queue). • Obtain a connection from the factory. • Create a session tied to the connection. • Look up the destination (topic or queue). • Create a message producer or a message consumer (specific for the topic or the queue). To get a connection to the provider and to get a destination to associate with your publisher/sender or your subscriber/receiver you have to use provider-specific parameters. JMS

  19. JMS Provider Specific Configuration There are three items that involve provider-specific stuff: • Getting the JNDI initial context • The name of the connection factories to use • Administration and naming conventions for destinations. JMS

  20. JMS API Programming Model • Administered Objects • Connection Factories • Destinations • Connections • Sessions • Message Producers • Message Consumers • Message Listeners • Message Selectors • Messages JMS

  21. JMS components JMS client JMS client Connection Connection Session Session Message server Consumer Producer Destination Message Message JMS

  22. JMS API Programming Model Administered Objects • Best maintained administratively rather than programmatically. • Technology underlying these objects is likely to be very different from one implementation of the JMS API to another. • JMS clients access these objects through interfaces that are portable. JMS

  23. JMS API Programming Model Connection Factory A connection factory is the object a client uses to create a connection with a provider. Every JMS Provider provides default factories. (QueueConnectionFactory, TopicConnectionFactory) Context ctx = new InitialContext(); QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory"); TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory"); JMS

  24. JMS API Programming Model Destinations A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes. For PTP destination is called Queue and for Pub/Sub it is referred to as Topic In addition to looking up a connection factory, client look up a destination also Topic myTopic = (Topic) ctx.lookup(“topic/MyTopic"); Queue myQueue = (Queue) ctx.lookup(“queue/My Queue”); JMS

  25. JMS API Programming Model Connections • It represents a virtual connection between a client and JMS provider service daemon. • Like connection factories there are two types of connections namely, QueueConnection and TopicConnection. QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(); TopicConnection topicConnection = topicConnectionFactory.createTopicConnection(); JMS

  26. JMS API Programming Model Sessions • It is a single threaded context for producing and consuming messages. • Clients use sessions to create message producers, message consumers and messages. • Provides a transactional context with which to group a set of sends and receives into an atomic unit of work. Types of sessions • Transacted • Non-transacted JMS

  27. JMS API Programming Model Sessions TopicSession topicSession = topicConnection.createTopicSession ( false, Session.AUTO_ACKNOWLEDGE); Here the first argument means that session is not transacted; the second means that the session automatically acknowledges messages when they have been received successfully. In case of transacted sessions, second argument is ignored. QueueSession queueSession = queueConnection.createQueueSession(true, 0); JMS

  28. JMS API Programming Model Sessions – JMS API Local Transactions • use local transactions to group message sends and receives. • The JMS API Session interface provides commit and rollback methods that you can use in a JMS client. A transaction commit means that all produced messages are sent and all consumed messages are acknowledged. A transaction rollback means that all produced messages are destroyed and all consumed messages are recovered and redelivered unless they have expired JMS

  29. JMS API Programming Model Sessions – Message Acknowledgment The successful consumption of a message ordinarily takes place in three stages. • The client receives the message. • The client processes the message. • The message is acknowledged. Acknowledgment is initiated either by the JMS provider or by the client, depending on the session acknowledgment mode. In Transacted sessions, acknowledgement happens automatically when a transaction is committed JMS

  30. JMS API Programming Model Message Producers A message producer is an object created by a session and is used for sending messages to a destination. Use a QueueSession to create a sender for the queue myQueue, and you use a TopicSession to create a publisher for the topic myTopic: QueueSender queueSender = queueSession.createSender(myQueue); TopicPublisher topicPublisher = topicSession.createPublisher(myTopic); Once you have created a message producer, you can use it to send messages queueSender.send(message); topicPublisher.publish(message); JMS

  31. JMS API Programming Model Message Consumer Amessage consumer is an object created by a session and is used for receiving messages sent to a destination. Use a QueueSession to create a receiver for the queue myQueue, and you use a TopicSession to create a subscriber for the topic myTopic: QueueReceiver queueReceiver = queueSession.createReceiver(myQueue); TopicSubscriber topicSubscriber = topicSession.createSubscriber(myTopic); Message delivery does not begin until you start the connection you created by calling the start method JMS

  32. JMS API Programming Model Synchronous Message Consumption Use the receive method to consume a message synchronously. You can use this method at any time after you call the start method: queueConnection.start(); Message m = queueReceiver.receive(); topicConnection.start(); Message m = topicSubscriber.receive(1000); // time out after a second JMS

  33. JMS API Programming Model Asynchronous Message Consumption Message Listeners • A message listener is an object that acts as an asynchronous event handler for messages. • It implements MessageListener Interface, which has only one method “onMessage(Message msg)” • MessageListener is not specific to a particular destination. • onMessage method should handle all exceptions. TopicListener topicListener = new TopicListener(); topicSubscriber.setMessageListener(topicListener); JMS

  34. JMS API Programming Model Message Selectors • Used for filtering out the messages received by the application. • Message selectors assign the work of filtering messages to the JMS provider rather than to the application. • A message selector is a SQL92 String that contains an expression. • A message selector cannot select messages on the basis of the content of the message body. Examples: phone LIKE ‘223’ JMSType IS NOT NULL name = ‘Tom’ JMS

  35. JMS API Programming Model Messages JMS Message has three parts : • Header - A JMS message header contains a number of predefined fields that contain values that both clients and providers use to identify and to route messages. • Properties (Optional) – to be used by message selectors. • Body (Optional) – JMS

  36. JMS API Programming Model JMS

  37. JMS API Programming Model Messages Sending a Message TextMessage message = queueSession.createTextMessage(); message.setText(msg_text); // msg_text is a String queueSender.send(message); Receiving a Message Message m = queueReceiver.receive(); if (m instanceof TextMessage) { TextMessage message = (TextMessage) m; System.out.println("Reading message: " + message.getText()); } else { // Handle error } JMS

  38. Message-Driven Beans • Introduced in EJB 2.0 Specs. • Not accessible to clients • Allows J2EE applications to process JMS messages asynchronously • A message-driven bean is a message listener that can reliably consume messages from a queue or a durable subscription. • Contains a method onMessage that is automatically called when a message arrives. • The main difference between a message-driven bean and other enterprise beans is that a message-driven bean has no home or remote interface. Rather, it has only a bean class. • Short lived and has no state. JMS

  39. Life Cycle of a MDB Does Not Exist 1.setMessageDrivenContext 2.ejbCreate ejbRemove Ready onMessage JMS

  40. MDB - Example import javax.ejb.*; import javax.naming.*; import javax.jms.*; public class MessageBean implements MessageDrivenBean,MessageListener { private transient MessageDrivenContext mdc = null; private Context context; public MessageBean() { System.out.println("In MessageBean.MessageBean()"); } public void setMessageDrivenContext(MessageDrivenContext mdc) { System.out.println("In MessageBean.setMessageDrivenContext()"); this.mdc = mdc; } public void ejbCreate() { System.out.println("In MessageBean.ejbCreate()"); } JMS

  41. MDB - Example public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message received: " + msg.getText()); } else { System.out.println("Message of wrong type: inMessage.getClass().getName()); } } catch (JMSException e) { System.err.println("MessageBean.onMessage: JMSException: " + e.toString()); mdc.setRollbackOnly(); } catch (Throwable te) { System.err.println("MessageBean.onMessage: Exception: " + te.toString()); } } public void ejbRemove() { System.out.println("In MessageBean.remove()"); } } JMS

  42. MDB -- Deployment ejb-jar.xml <ejb-jar> <enterprise-beans> <message-driven> <ejb-name>MessageEJB</ejb-name> <ejb-class>MessageBean</ejb-class> <transaction-type>Container</transaction-type> <message-selector>varX=‘123’</message-selector> <message-driven-destination> <destination-type>javax.jms.Queue</destination-type> </message-driven-destination> </message-driven> </enterprise-beans> </ejb-jar> JMS

  43. MDB - Deployment Jboss.xml <jboss> <enterprise-beans> <message-driven> <ejb-name> MessageEJB</ejb-name> <destination-jndi-name>queue/MyQueue</destination-jndi-name> </message-driven> </enterprise-beans> </jboss> JMS

  44. Publisher Sample See MyTopicPublisher.java for source. • Perform a JNDI API lookup of the TopicConnectionFactory and topic • topic = (Topic) jndiContext.lookup(topicName); • Create a connection and a session • topicConnection = topicConnectionFactory.createTopicConnection(); • topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); • Create a TopicPublisher • topicPublisher = topicSession.createPublisher(topic); • Create a TextMessage • Message = topicSession.createTextMessage(); • message.setText("This is message " + (i + 1)); • Publishe one or more messages to the topic • topicPublisher.publish(message); • Close the connection, which automatically closes the session and TopicPublisher JMS

  45. Subscriber Sample See MyTopicSubscriber.java for source. • Perform a JNDI API lookup of the TopicConnectionFactory and topic (same as publisher) • Create a connection and a session (same as publisher) • Create a TopicSubscriber • topicSubscriber = topicSession.createSubscriber(topic); • Create an instance of the TextListener class and registers it as the message listener for the TopicSubscriber • topicListener = new TextListener(); • topicSubscriber.setMessageListener(topicListener); • Start the connection, causing message delivery to begin • topicConnection.start(); • Close the connection, which automatically closes the session and TopicSubscriber • topicConnection.close(); JMS

  46. TextListener Sample • public void onMessage(Message message) { • TextMessage msg = null; • try { • if (message instanceof TextMessage) { • msg = (TextMessage) message; • System.out.println("Reading message: " + msg.getText()); • } else { • System.out.println("Message of wrong type: " + • message.getClass().getName()); • } • } catch (JMSException e) { • System.out.println("JMSException in onMessage(): " + e.toString()); • } catch (Throwable t) { • System.out.println("Exception in onMessage():" + t.getMessage()); • } • } JMS

  47. References • http://java.sun.com/products/jms/tutorial/1_3_1-fcs/doc/jmsj2ee.html • http://edocs.bea.com/wls/docs81/jms/implement.html • http://java.sun.com/products/jms/tutorial/1_3_1-fcs/doc/jms_tutorialTOC.html JMS

More Related