jms (java messaging service)
DESCRIPTION
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. - PowerPoint PPT PresentationTRANSCRIPT
JMS 1
JMS(Java Messaging Service)
JMS 2
Motivation Performance Reliability Support for multiple senders & receivers.
Application
Application
RMI
Application
Messaging Middleware
Application
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 IntroductionJMS 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)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 :Example :An e-commerce application might include a 1. Web front-end for customer order entry 2. A warehouse then receives the order, packages the
appropriate items, 3. 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 ArchitectureA JMS application is composed of the following
parts.
JMS Provider JMS Clients Messages Administered Objects (Connection Factories,
Queues)
JMS 9
JMS messaging domainsThe 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
JMS messaging domains
Consumer 1
Producer 1
Producer 2Queue
Producer 1
Producer 2
Consumer 1
Consumer 2
Topic
Point to Point
Publisher - Subscriber
JMS 11
Point-to-PointPoint-to-PointPoint-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 SubscribePublish 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 store
MessageServer
Undelivered messages delivered to Subscriber2 when reconnected
PERSISTENT message
Durable Subscriber1(connected)
Producer
Durable Subscriber2
(not connected)
JMS 16
Message ConsumptionMessages can be consumed in either of two ways:
SynchronouslySynchronously. 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.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 ModelThe way to operate within the JMS framework is as follows:1. Get the JNDI initial context.2. Look up a connection factory (for the right type of
destination, topic or queue).3. Obtain a connection from the factory.4. Create a session tied to the connection.5. Look up the destination (topic or queue).6. 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:
1. Getting the JNDI initial context2. The name of the connection factories to use3. 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
ConnectionSession
Producer
JMS client
ConnectionSession
ConsumerMessage server
DestinationMessage
Message
JMS 22
JMS API Programming ModelAdministered ObjectsAdministered 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 ModelConnection FactoryConnection 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 ModelDestinationsDestinationsA 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 ModelConnectionsConnections 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 ModelSessionsSessions• 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 sessionsTypes of sessions
• Transacted
• Non-transacted
JMS 27
JMS API Programming ModelSessionsSessionsTopicSession 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 ModelSessions – JMS API Local TransactionsSessions – 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 ModelSessions – Message AcknowledgmentSessions – 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 ModelMessage ProducersMessage 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 ModelMessage ConsumerMessage Consumer
A message 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 ModelSynchronous Message ConsumptionSynchronous 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 ModelAsynchronous Message ConsumptionAsynchronous Message Consumption
Message ListenersMessage 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 ModelMessage SelectorsMessage 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 NULLname = ‘Tom’
JMS 35
JMS API Programming ModelMessagesMessagesJMS 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
Message type Message bodyTextMessage A standard Java string
ObjectMessage A serializable Java object
MapMessage A set of name/ value pairs where values are Java
primitives
StreamMessage A stream of Java primitives
BytesMessage A stream of uninterrupted bytes
JMS 37
JMS API Programming ModelMessagesMessagesSending a MessageTextMessage message = queueSession.createTextMessage();message.setText(msg_text); // msg_text is a StringqueueSender.send(message);
Receiving a MessageMessage 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
Ready
1. setMessageDrivenContext2. ejbCreate ejbRemov
e
onMessage
JMS 40
MDB - Exampleimport 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 - Examplepublic 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 -- Deploymentejb-jar.xmlejb-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 - DeploymentJboss.xmlJboss.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 SamplePublisher SampleSee MyTopicPublisher.java for source.1. Perform a JNDI API lookup of the TopicConnectionFactory and topic
topic = (Topic) jndiContext.lookup(topicName);
2. Create a connection and a session topicConnection = topicConnectionFactory.createTopicConnection();topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
3. Create a TopicPublisher topicPublisher = topicSession.createPublisher(topic);
4. Create a TextMessage Message = topicSession.createTextMessage();message.setText("This is message " + (i + 1));
5. Publishe one or more messages to the topictopicPublisher.publish(message);
6. Close the connection, which automatically closes the session and TopicPublisher
JMS 45
Subscriber SampleSubscriber SampleSee MyTopicSubscriber.java for source.1. Perform a JNDI API lookup of the TopicConnectionFactory and
topic (same as publisher)2. Create a connection and a session (same as publisher)3. Create a TopicSubscriber
topicSubscriber = topicSession.createSubscriber(topic);
4. Create an instance of the TextListener class and registers it as the message listener for the TopicSubscriber
topicListener = new TextListener();topicSubscriber.setMessageListener(topicListener);
5. Start the connection, causing message delivery to begin topicConnection.start();
6. Close the connection, which automatically closes the session and TopicSubscriber
topicConnection.close();
JMS 46
TextListener SampleTextListener Sample1. public void onMessage(Message message) {2. TextMessage msg = null;3. 4. try {5. if (message instanceof TextMessage) {6. msg = (TextMessage) message;7. System.out.println("Reading message: " + msg.getText());8. } else {9. System.out.println("Message of wrong type: " +10. message.getClass().getName());11. }12. } catch (JMSException e) {13. System.out.println("JMSException in onMessage(): " + e.toString());14. } catch (Throwable t) {15. System.out.println("Exception in onMessage():" + t.getMessage());16. }17. }
JMS 47
ReferencesReferences http://java.sun.com/products/jms/tutorial/1_3_1-fcs/doc/j
msj2ee.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