|
YOUR FEEDBACK
Did you read today's front page stories & breaking news?
SYS-CON.TV |
TOP THREE LINKS YOU MUST CLICK ON Feature Using the Java Message Service with BEA WebLogic
Using the Java Message Service with BEA WebLogic
By: Scott Grant
Jan. 30, 2004 12:00 AM
In the last couple of years Sun has introduced a number of APIs targeted toward enterprise application development. One of the most exciting of these is the Java Message Service, or JMS. The JMS API is designed to do for messaging in the enterprise what JNDI does for naming and directory services and JDBC does for database access. JMS is an API that's designed to provide a common facility for enterprise messaging, leaving the underlying implementation of the messaging to whatever application server or other enterprise messaging software technology you wish to use. This is an exciting advance for those involved with the creation or use of message-oriented middleware (MOM) and especially for Java developers who need to utilize such facilities within their own products. With JMS you should be able to write one set of code for messaging against the JMS API and then use it across any messaging system provider that offers JMS support. In this article I'll show you how to create a series of message producers and consumers that utilize most of the functions of the JMS API using persistent topics and queues, creating temporary destinations, filtering via message selectors, and so on. I'll implement these examples against one of the first vendor implementations of JMS, the one provided with the WebLogic application server from BEA (details on this server and configuring JMS are available online in the file "install.txt" at www.JavaDevelopersJournal.com). In this process I'll take you through the necessary steps to implement these applications, including the modifications to the application server to support the example code you'll create. Before you continue with the example code here, I recommend that you first obtain and install the latest release of the BEA/WebLogic application server. You can download a free 30-day trial copy from BEA at www.weblogic.com.
The Code
The Java Message Service
JMS was also designed to be flexible enough to provide this wide support for existing messaging systems while remaining portable. As a result, it doesn't support every possible messaging option from every messaging system. While you may be familiar with any given MOM product, it's not automatic that JMS will support every aspect of that product. The primary concept in JMS is that of Destinations. A Destination is nothing more than an association for message producers and message consumers. Destinations break down into two types, Topics and Queues. Separate interfaces defined for each Destination type allow a provider to support one or both, depending on their messaging facility. A Topic is designed for publish/subscribe messaging, and a Queue is designed for client-to-client (point-to-point) messaging. Both Destination types support persistence. JMS also provides support for transactions. Transactions enable you to support commits or rollbacks on your messaging operations. Thus, if you have a failure within the boundaries of your transaction, you can roll back all of the messaging operations that took place within the boundaries of that transaction. Likewise, if everything completes successfully, you can perform a commit on your messaging operations to make them durable. As JMS Transactions are beyond the scope of this article, I leave you to investigate that aspect of JMS on your own.
Initializing JMS
Don't worry if this seems a little confusing the code examples will make it easy to understand. You may also create your own Factory objects in WebLogic instead of using the default Factories; this is done within the weblogic.properties file. User-defined Factories are discussed later, in the section on Topics, while the details of defining your own Factories are contained in the "install.txt" file included online with the article source code. The following code from within the Sender.java example shows how you initialize JMS and obtain the default ConnectionFactory for Queues from JNDI:
public final String JMS_FACTORY = "javax.jms.QueueConnectionFactory";
...
queueFx = (QueueConnectionFactory) initCtx.lookup(JMS_FACTORY);
The name of the default ConnectionFactory for Queues is passed in to the lookup() method of the initial JNDI naming context. A reference to an implementation of QueueConnectionFactory is then returned to us from the WebLogic application server (the getInitialContext() method in the Sender.java sample code that shows the details of initializing JNDI and obtaining the initial naming context from WebLogic you can obtain details on the API from Sun's Web site at: http://java.sun.com/products/jndi/1.2/javadoc/index.html). Because ConnectionFactories are administered objects, the WebLogic application server takes care of creating default ConnectionFactories for Queues and Topics, as well as any user-defined Factories, and binding them to names in the WebLogic JNDI implementation for lookup by client code. Thus the name in JNDI for the default ConnectionFactory for Queues is "javax.jms.QueueConnectionFactory" and a lookup of this name through JNDI will return a reference to a default implementation of this interface, provided by WebLogic. There is a default ConnectionFactory for Topics as well, and it follows the same format; "javax.jms.TopicConnectionFactory". A lookup through JNDI will return you a reference to a default implementation of TopicConnectionFactory, also provided by WebLogic.
Connections
Sessions A Session may be transacted or not, and you typically set this by passing a boolean parameter to the appropriate creation method on the Connection. You also typically pass a parameter to the Connection's Session creation method that sets the message acknowledgment mode of the Session being created this mode specifies whether the client or the consumer will acknowledge any messages it receives (this parameter will be ignored if transactioning is being used). Other methods provided by Session are various message creation methods that let you create JMS messages of specific types containing text, bytes, properties or even serialized Java objects (more on the Message interface below). See Figure 1 for a diagram of the actual JMS interface inheritance and creation relationships see also the code in Listing 1.
Figure 1:
Destinations For the purposes of this article, our Destinations are created in advance, through the weblogic.properties file. Destinations defined in this file will be created by the WebLogic application server when it starts up, and will be made available to your client code through JNDI. Listing 1 shows the code from the Sender.java file, which demonstrates how to create a QueueConnection and a QueueSession, and retrieve our own Destination a Queue we defined in weblogic.properties named "jdj.article.queue.sender" the same as the package hierarchy for the Sender application.
Message Consumers and Message Producers
Once you've created your MessageConsumer and/or MessageProducer, you have everything in place to begin receiving and/or sending messages. Since the creation of consumers and producers is specific to either Queues or Topics, I'll discuss the process for both types in the relevant sections below, specific to the Destination type.
Messages
Persistence
Queues
In reality, you can have multiple clients sending to a Queue, but you should never have more than one application consuming messages from that Queue. If you have more than one Consumer on a Queue, there's no guarantee about which Consumer will receive the message, but it'll only be one. If you need multiple Consumers on a Destination and would like all of them to receive the same message, you should use a Topic (see the following page). The Sender.java and Receiver.java files contain the code that shows how to use a Queue. The code demonstrates the initialization process for JMS and retrieval of our predefined Queue, and how to create both a MessageProducer and a MessageConsumer for sending and receiving messages on the Queue. There are two specific interfaces for consuming and producing messages on a Queue. QueueSender, which is returned from a QueueSession via a call to one of the createQueueSender() methods of the QueueSession, is used to send messages to the Queue. QueueReceiver, which is returned from a QueueSession via a call to one of the createQueueReceiver() methods of the QueueSession, is used to receive messages from the Queue. Listing 2 is the code from the sendMsg method of Sender.java that shows how you create a MessageProducer from your Session, then construct a TextMessage and send it. In this code we're creating a QueueSender, then creating a TextMessage with text retrieved from a TextField in the UI of the application. We then use the QueueSender method "send" to deliver the message. There are two ways to handle the receipt of incoming messages on a MessageConsumer synchronous and asynchronous. The first step is to create the MessageConsumer itself; the next is to decide whether you want synchronous or asynchronous message delivery on the Consumer. After you create a MessageConsumer from your Session, if you want to synchronously receive the next message produced for the Destination, you can call the receive method on your MessageConsumer this method takes no parameters and will block until the next Message is received, which it will return to the caller. For asynchronous message receipt, you register an implementation of the MessageListener interface with your MessageConsumer. This goes for both Topics and Queues. MessageListener has one method that you must implement, onMessage, which receives one parameter, a Message. This method will be called on your implementation of onMessage for every message delivered to the Destination. This is demonstrated in the implementation of onMessage in both Sender.java and Receiver.java. In Receiver.java we have the following code in the initializeJMS method, which creates the MessageConsumer (a QueueReceiver) and sets the implementation of MessageListener:
// Create a Receiver for the Queue...
// Set the listener (this class) Once the Connection's "start" method is called, messages will begin to come in to the Consumer as they arrive at the Destination.
ReplyTo Using Temporary Queues One of the properties of Message is the JMSReplyTo property. This property is intended to be used for this purpose. You can create a temporary Queue or Topic and place it into the JMSReplyTo property of the Message. Consumers who receive this message have a private, temporary Destination that they can use to respond to the sender. This is demonstrated by two methods, one in each of the files. In Sender.java we have the following sections of code, which create the temporary Queue and place it in the JMSReplyTo property of the TextMessage:
// Create a temporary queue for replies...
The line of code above is found in the initializeJMS method of Sender.java. This code creates a temporary Queue on application start-up that will exist for the lifetime of the application. The next line of code, found in the sendMsg method of Sender.java, shows how to set the JMSReplyTo property to contain the temporary Queue.
// Set ReplyTo to temporary queue... When this message is received by the QueueReceiver of Receiver.java, the temporary Queue is extracted from the JMSReplyTo field, and a QueueSender is constructed by the application to send a response message back to Sender.java. This demonstrates how to use the properties of a JMS Message and shows the usefulness of a private, temporary Destination. It also demonstrates how clients can be both Producers and Consumers of messages. The following code from Receiver.java demonstrates how to handle the extraction of the temporary Queue from the JMS Message; this code is found in the onMessage method:
// Get the temporary queue from the JMSReplyTo The following block from the sendReplyToMsg method shows how to create a QueueSender and send the reply:
// create a Sender for the temporary queue
TextMessage msg = session.createTextMessage();
...
// Send the message to the temporary queue...
Topics
The creation process for MessageProducers and MessageConsumers of a Topic is similar to that of a Queue. You use your Session to create the TopicPublishers and TopicSubscribers. These mirror the QueueSender and QueueReceiver in that each provides Topic-specific capabilities and implements the base MessageProducer and MessageConsumer interfaces. The creation process for a TopicPublisher is nearly identical to that of the QueueSender. Following is the code from the sendMsg method of Publisher.java that shows the creation of a TopicPublisher and how to publish the message to the Topic:
// create a Publisher if there isn't one...
TextMessage msg = session.createTextMessage();
...
// Publish it to the topic...
Durable Subscribers An application that creates a TopicSubscriber via a call to the createDurableSubscriber method of a TopicSession must pass in a durable subscriber name (a string) as one of its parameters; for instance, you could set the durable subscriber name to the name of the user currently logged into the application, and so on. This name will uniquely identify a particular subscriber to a Topic (in conjunction with a unique Client ID for the Connection/Session). Once this durable subscriber has registered with the Topic, the Topic will persistently ensure delivery of messages to that subscriber. This means that if a particular durable subscriber is unavailable, messages will be held until the next time that durable subscriber (with the same unique, durable subscriber name and Client ID) registers as a Consumer. The Subscriber.java file demonstrates the creation of durable subscribers and allows you to use a default subscriber name or to set this identifier from the command line (see the "readme.txt" file for further details on running the application and demonstrating the message persistence with durable subscribers). The following code fragment from the initializeJMS method of Subscriber.java shows how to create a durable subscriber from your TopicSession:
subscriber = session.createDurableSubscriber(
// Set the listener (this class) TopicSubscribers that aren't created as durable subscribers won't receive messages persistently, and will receive them only while they're running. For further details on durable subscribers, and Topics in general, please see Sun's JMS documentation. One other item about the preceding code: note that the third parameter passed to the method is SELECTOR. This is where message selectors are associated with a Consumer (see below for details on message selectors).
Filtering Using Message Selectors public final String SELECTOR = "JMSType = 'TOPIC_PUBLISHER'"; This selector examines the JMSType property of the incoming message from our Topic and determines whether the value is equal to TOPIC_PUBLISHER. If it is, the message is passed to our MessageListener implementation; if it isn't, the message is ignored. See the "readme.txt" file for details on running the applications and demonstrating this behavior. I also encourage you to check out Sun's JMS documentation.
Summary
YOUR FEEDBACK
BEA WEBLOGIC LATEST STORIES
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS BREAKING NEWS FROM THE WIRES
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||