Download
FAQ History |
API
Search Feedback |
The JMS API Programming Model
The basic building blocks of a JMS application consist of
- Administered Objects: connection factories and destinations
Figure 33-5 shows how all these objects fit together in a JMS client application.
Figure 33-5 The JMS API Programming Model
This section describes all these objects briefly and provides sample commands and code snippets that show how to create and use the objects. The last subsection briefly describes JMS API exception handling.
Examples that show how to combine all these objects in applications appear in later sections. For more details, see the JMS API documentation, which is part of the J2EE API documentation.
Administered Objects
Two parts of a JMS application--destinations and connection factories--are best maintained administratively rather than programmatically. The technology underlying these objects is likely to be very different from one implementation of the JMS API to another. Therefore, the management of these objects belongs with other administrative tasks that vary from provider to provider.
JMS clients access these objects through interfaces that are portable, so a client application can run with little or no change on more than one implementation of the JMS API. Ordinarily, an administrator configures administered objects in a JNDI namespace, and JMS clients then look them up by using the JNDI API. J2EE applications always use the JNDI API.
With the Sun Java System Application Server Platform Edition 8, you use the Admin Console to create JMS administered objects in the form of resources. You can also use the
asadmin
command.Connection Factories
A connection factory is the object a client uses to create a connection to a provider. A connection factory encapsulates a set of connection configuration parameters that has been defined by an administrator. Each connection factory is an instance of either the
QueueConnectionFactory
or theTopicConnectionFactory
interface.To learn how to use the Admin Console to create connection factories, see Creating JMS Administered Objects.
At the beginning of a JMS client program, you usually perform a JNDI lookup of the connection factory. The connection factory itself is specific to one domain or the other. However, you normally cast and assign it to a
ConnectionFactory
object.For example, the following code fragment obtains an
InitialContext
object and uses it to look up theQueueConnectionFactory
and theTopicConnectionFactory
by name. Then it assigns each to aConnectionFactory
object:Context ctx = new InitialContext(); ConnectionFactory connectionFactory1 = (ConnectionFactory) ctx.lookup("jms/QueueConnectionFactory"); ConnectionFactory connectionFactory2 = (ConnectionFactory) ctx.lookup("jms/TopicConnectionFactory");In a J2EE application, JMS administered objects are normally placed in the
jms
naming subcontext.Destinations
A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes. In the PTP messaging domain, destinations are called queues. In the pub/sub messaging domain, destinations are called topics.
Creating destinations using the Application Server is a two-step process. You create a JMS destination resource that specifies the JNDI name of the destination. You also create a physical destination to which the JNDI name refers.
To learn how to use the Admin Console to create physical destinations and destination resources, see Creating JMS Administered Objects.
A JMS application can use multiple queues or topics (or both).
In addition to looking up a connection factory in a client program, you usually look up a destination. Like connection factories, destinations are specific to one domain or the other. You normally assign the destination to a
Destination
object. To preserve the semantics of queues and topics, however, you cast the object to a destination of the appropriate type.For example, the following line of code performs a JNDI lookup of the previously created topic
jms/MyTopic
and assigns it to aDestination
object, after casting it to aTopic
object:The following line of code looks up a queue named
jms/MyQueue
and assigns it to aDestination
object, after casting it to aQueue
object:With the common interfaces, you can mix or match connection factories and destinations. That is, you can look up a
QueueConnectionFactory
and use it with aTopic
, and you can look up aTopicConnectionFactory
and use it with aQueue
. The behavior of the application will depend on the kind of destination you use and not on the kind of connection factory you use.Connections
A connection encapsulates a virtual connection with a JMS provider. A connection could represent an open TCP/IP socket between a client and a provider service daemon. You use a connection to create one or more sessions.
Connections implement the
Connection
interface. When you have aConnectionFactory
object, you can use it to create aConnection
:Before an application completes, you must close any connections that you have created. Failure to close a connection can cause resources not to be released by the JMS provider. Closing a connection also closes its sessions and their message producers and message consumers.
Before your application can consume messages, you must call the connection's
start
method; for details, see Message Consumers. If you want to stop message delivery temporarily without closing the connection, you call thestop
method.Sessions
A session is a single-threaded context for producing and consuming messages. You use sessions to create message producers, message consumers, and messages. Sessions serialize the execution of message listeners; for details, see Message Listeners.
A session provides a transactional context with which to group a set of sends and receives into an atomic unit of work. For details, see Using JMS API Local Transactions.
Sessions implement the
Session
interface. After you create aConnection
object, you use it to create aSession
:The first argument means that the session is not transacted; the second means that the session automatically acknowledges messages when they have been received successfully. (For more information, see Controlling Message Acknowledgment.)
To create a transacted session, use the following code:
Here, the first argument means that the session is transacted; the second indicates that message acknowledgment is not specified for transacted sessions. For more information on transactions, see Using JMS API Local Transactions. For information about the way JMS transactions work in J2EE applications, see Using the JMS API in a J2EE Application.
Message Producers
A message producer is an object that is created by a session and used for sending messages to a destination. It implements the
MessageProducer
interface.You use a
Session
to create aMessageProducer
for a destination. Here, the first example creates a producer for the destinationmyQueue
, and the second for the destinationmyTopic
:MessageProducer producer = session.createProducer(myQueue); MessageProducer producer = session.createProducer(myTopic);You can create an unidentified producer by specifying
null
as the argument tocreateProducer
. With an unidentified producer, you can wait to specify which destination to send the message to until you send a message.After you have created a message producer, you can use it to send messages by using the
send
method:You must first create the messages; see Messages.
If you created an unidentified producer, use an overloaded
send
method that specifies the destination as the first parameter. For example:Message Consumers
A message consumer is an object that is created by a session and used for receiving messages sent to a destination. It implements the
MessageConsumer
interface.A message consumer allows a JMS client to register interest in a destination with a JMS provider. The JMS provider manages the delivery of messages from a destination to the registered consumers of the destination.
For example, you use a
Session
to create aMessageConsumer
for either a queue or a topic:MessageConsumer consumer = session.createConsumer(myQueue); MessageConsumer consumer = session.createConsumer(myTopic);You use the
Session.createDurableSubscriber
method to create a durable topic subscriber. This method is valid only if you are using a topic. For details, see Creating Durable Subscriptions.After you have created a message consumer, it becomes active, and you can use it to receive messages. You can use the
close
method for aMessageConsumer
to make the message consumer inactive. Message delivery does not begin until you start the connection you created by calling itsstart
method. (Remember always to call thestart
method; forgetting to start the connection is one of the most common JMS programming errors.)You use the
receive
method to consume a message synchronously. You can use this method at any time after you call thestart
method:connection.start(); Message m = consumer.receive(); connection.start(); Message m = consumer.receive(1000); // time out after a secondTo consume a message asynchronously, you use a message listener, described in Message Listeners.
Message Listeners
A message listener is an object that acts as an asynchronous event handler for messages. This object implements the
MessageListener
interface, which contains one method,onMessage
. In theonMessage
method, you define the actions to be taken when a message arrives.You register the message listener with a specific
MessageConsumer
by using thesetMessageListener
method. For example, if you define a class namedListener
that implements theMessageListener
interface, you can register the message listener as follows:After you register the message listener, you call the
start
method on theConnection
to begin message delivery. (If you callstart
before you register the message listener, you are likely to miss messages.)When message delivery begins, the JMS provider automatically calls the message listener's
onMessage
method whenever a message is delivered. TheonMessage
method takes one argument of typeMessage
, which your implementation of the method can cast to any of the other message types (see Message Bodies).A message listener is not specific to a particular destination type. The same listener can obtain messages from either a queue or a topic, depending on the type of destination for which the message consumer was created. A message listener does, however, usually expect a specific message type and format. Moreover, if it needs to reply to messages, a message listener must either assume a particular destination type or obtain the destination type of the message and create a producer for that destination type.
Your
onMessage
method should handle all exceptions. It must not throw checked exceptions, and throwing aRuntimeException
is considered a programming error.The session used to create the message consumer serializes the execution of all message listeners registered with the session. At any time, only one of the session's message listeners is running.
In the J2EE platform, a message-driven bean is a special kind of message listener. For details, see Using Message-Driven Beans.
Message Selectors
If your messaging application needs to filter the messages it receives, you can use a JMS API message selector, which allows a message consumer to specify the messages it is interested in. Message selectors assign the work of filtering messages to the JMS provider rather than to the application. For an example of an application that uses a message selector, see A J2EE Application That Uses the JMS API with a Session Bean.
A message selector is a
String
that contains an expression. The syntax of the expression is based on a subset of the SQL92 conditional expression syntax. The message selector in the example selects any message that has aNewsType
property that is set to the value'Sports'
or'Opinion'
:The
createConsumer
andcreateDurableSubscriber
methods allow you to specify a message selector as an argument when you create a message consumer.The message consumer then receives only messages whose headers and properties match the selector. (See Message Headers, and Message Properties.) A message selector cannot select messages on the basis of the content of the message body.
Messages
The ultimate purpose of a JMS application is to produce and to consume messages that can then be used by other software applications. JMS messages have a basic format that is simple but highly flexible, allowing you to create messages that match formats used by non-JMS applications on heterogeneous platforms.
A JMS message has three parts: a header, properties, and a body. Only the header is required. The following sections describe these parts:
- Message Properties (optional)
- Message Bodies (optional)
For complete documentation of message headers, properties, and bodies, see the documentation of the
Message
interface in the API documentation.Message Headers
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. Table 33-1 lists the JMS message header fields and indicates how their values are set. For example, every message has a unique identifier, which is represented in the header field
JMSMessageID
. The value of another header field,JMSDestination
, represents the queue or the topic to which the message is sent. Other fields include a timestamp and a priority level.Each header field has associated setter and getter methods, which are documented in the description of the
Message
interface. Some header fields are intended to be set by a client, but many are set automatically by thesend
or thepublish
method, which overrides any client-set values.
Message Properties
You can create and set properties for messages if you need values in addition to those provided by the header fields. You can use properties to provide compatibility with other messaging systems, or you can use them to create message selectors (see Message Selectors). For an example of setting a property to be used as a message selector, see A J2EE Application That Uses the JMS API with a Session Bean.
The JMS API provides some predefined property names that a provider can support. The use of either of these predefined properties or user-defined properties is optional.
Message Bodies
The JMS API defines five message body formats, also called message types, which allow you to send and to receive data in many different forms and provide compatibility with existing messaging formats. Table 33-2 describes these message types.
The JMS API provides methods for creating messages of each type and for filling in their contents. For example, to create and send a
TextMessage
, you might use the following statements:TextMessage message = session.createTextMessage(); message.setText(msg_text); // msg_text is a String producer.send(message);At the consuming end, a message arrives as a generic
Message
object and must be cast to the appropriate message type. You can use one or more getter methods to extract the message contents. The following code fragment uses thegetText
method:Message m = consumer.receive(); if (m instanceof TextMessage) { TextMessage message = (TextMessage) m; System.out.println("Reading message: " + message.getText()); } else { // Handle error }Exception Handling
The root class for exceptions thrown by JMS API methods is
JMSException
. CatchingJMSException
provides a generic way of handling all exceptions related to the JMS API. TheJMSException
class includes the following subclasses, which are described in the API documentation:
IllegalStateException
InvalidClientIDException
InvalidDestinationException
InvalidSelectorException
JMSSecurityException
MessageEOFException
MessageFormatException
MessageNotReadableException
MessageNotWriteableException
ResourceAllocationException
TransactionInProgressException
TransactionRolledBackException
All the examples in the tutorial catch and handle
JMSException
when it is appropriate to do so.
Download
FAQ History |
API
Search Feedback |
All of the material in The J2EE(TM) 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.