Use Java Message Service In BEA WebLogic

Original link: http://www.cnblogs.com/kapok/archive/2005/10/15/255324.html
E Original text link: http://wldj.sys-con.com/read/42639.htm?CFID=245214&CFTOKEN=EF8844DA-12E2-866A-6C138B6CF9CDCCA1
Original Chinese link: http://dev2dev.bea.com.cn/ techdoc / 2005033105.html



 in the last two years, Sun introduced a lot of API for enterprise application development. One of the most exciting is the Java Message Service, or JMS. JMS API for messaging in the enterprise and design, which, JNDI mission is to provide naming and directory services for directory services, and JNBC mission is to provide database access. JMS enterprise messaging in order to provide a universal tool designed API, it does not take to send messages to any underlying application server implementation does not consider you wish to use other enterprise messaging software technology. For developers who create or use message-oriented middleware (MOM), especially those Java developers need to use these tools in their products, this is a big step forward. By JMS, you should be able to write one set of code for messaging JMS API, then use the code in any messaging system provides JMS supports.
  In this article, I'll show you how to create a series of message producers and consumers, they make use of most of the JMS API function to use persistent storage of topics and queues, create a temporary destination, filter messages by message selector ,and many more. I will achieve these examples in the realization of the first supplier of JMS, the detailed information (about the server and the configuration of JMS with BEA's WebLogic application server provided with the realization that, from www.JavaDevelopersJournal.com The "install.txt" online file obtained). In this process, I will take you to go through the steps necessary to implement these applications, which include modifications to the application server to support the sample code you will create.
  Before you proceed to create the following sample code, we recommend that you obtain and install the latest version of BEA / WebLogic application server. BEA's Web site can be from http://ecommerce.bea.com/index.jsp free trial downloads.

Codes
  including online source files included, a total of four source files show how to use two different types of messages passed JMS: publish / subscribe and point to point. Sender.java and Receiver.java shows how to use Queue to-point messaging JMS, whereas Publisher.java and Subscriber.java shows how to use Topic publish / subscribe messaging. "Readme.txt" file (also available online) contains various commands to run the application as well as the latest information about the code. Before attempting to run these applications, be sure to read the "install.txt" file, and make the necessary changes to the WebLogic server according to the instructions. Because the sample code also contains more details on some of the comments and JMS, this article can not fully describe these details, so we encourage readers to examine the source code and run these applications.

Java Message Service
  Java Message Service is designed as a set of interfaces that will MOM vendors and others who wish to support messaging vendor (application server vendors, database server vendor, and so on). These interfaces hope to achieve code for the client application provides a common API, for possible, given the number of underlying messaging system messaging.
  At the same time, JMS design is very flexible, it can provide extensive support for existing messaging system while maintaining portability. Thus, it does not support each messaging system messaging every possible choice. Although you may be familiar with any given MOM product, but JMS does not automatically support every aspect of the product.
  The main concept is JMS Destination. Destination is only an association between news producers and news consumers. Destination is divided into two types: Topic and Queue. Destination separate interfaces for each type definitions allow vendors to support one type or both types are supported, depending on the vendor's messaging tool. Topic for publish / subscribe messaging and design, and the Queue messages for customers to customers (point to point) transmission design. Both types support Destination persistence. JMS also provides support for transactions. Transaction support messaging enables you to commit and rollback operations. Therefore, if the operations in the transaction fails, you can roll back pass operation with the message of what happened in the transaction. Similarly, if everything is going well, you can submit these messaging operations to make them durable available. Because JMS transactions beyond the scope of this article, so I'll let yourself go to study these aspects of JMS.

Initialization JMS
connection factory

  To initialize the JMS, you need to use the ConnectionFactory, it is a marker interface, wherein there is no way, and may be extended by TopicConnectionFactory or QueueConnectionFactory. Vendors implement these interfaces in a factory or two interfaces are implemented in order to provide access to service delivery to achieve its particular message. WebLogic provides a general realization of each type of Factory. Factory, as well as Topic and Queue, are considered to be "managed" objects, they are created WebLogic server (in our example, we will use the WebLogic JMS implementation) at boot time. Then, these managed objects can be retrieved through JNDI. JNDI naming context may also be used to retrieve the managed objects.
  If this seems a little to make you feel confused, do not worry, the sample code will make you easily understand them. You can also create your own Factory in WebLogic objects, rather than using the default Factory, this operation is done in weblogic.properties file. User-defined Factory will be discussed later, this section focuses Topic, define the details of their Factory included in the "install.txt" file, the file and the source code for this article can be found online.
  The following code from Sender.java example, it will show you how to initialize JMS, and how to get from JNDI Queue ConnectionFactory:

public JMS_FACTORY Final String = "javax.jms.QueueConnectionFactory";
...
queueFx = (the QueueConnectionFactory) initCtx. lookup (JMS_FACTORY);

  The default name of the ConnectionFactory Queue is transmitted to the initial naming context JNDI lookup () method. References to QueueConnectionFactory will then return to the realization of our (getInitialContext Sender.java sample code () method shows the initialization and JNDI initial naming context to obtain details from the WebLogic from WebLogic application server that you can get from Sun's website on . API details URL is: http://java.sun.com/products/jndi/1.2/javadoc/index.html ).
  Because ConnectionFactories is a managed object, so the responsibility of the WebLogic application server Queue, Topic, and all user-defined Factory creates a default ConnectionFactories, and bind them together with the implementation of the WebLogic JNDI name for lookup by client code. Therefore, in JNDI, Queue ConnectionFactory default name is "javax.jms.QueueConnectionFactory", in the name of a JNDI lookup time, will return a reference to the default implementation of the interface, and the reference is provided by WebLogic. Topic also has a default ConnectionFactory, it follows the same format, "javax.jms.TopicConnectionFactory". To find the default TopicConnectionFactory Returns a reference implementation, it is also provided by WebLogic JNDI's.

connection
  After successfully creating the correct ConnectionFactory, the next step will be to create a "connection", which is an interface JMS defined that a connection to the underlying messaging provider client connections. ConnectionFactory responsible for returning the message can be transmitted with the underlying communication system Connection achieved. The client is usually only use a single connection. According to the JMS document, Connection's aim is "to use JMS provider package open connection", and that "the client and the service provider between open TCP routines / IP sockets. The document also noted that Connection should be carried out customer local machine authentication, in addition to a number of other matters, the client can also specify a unique identifier. ConnectionFactories like, like, Connections, there are two types, depending on the type of Destination TopicConnection .QueueConnection and you will use both extended basic Connection interface, usually, you can only use one of them, which one to use depends on the way to create a messaging client will use .Connection is done by ConnectionFactory .Connection contains two important ways: start and stop, start and stop send and receive messages during the connection. see full list of code blocks in 1.

session
  Once a Connection from the ConnectionFactory, you must create one or more sessions from Connection. Session is the basic interface, while there are two specific extensions to the basic interface Destination interface: QueueSession and the TopicSession, they can provide specific Session Queue method or the Topic. Session is (if Destination Type is QueueSession, it will create a Queue for producers and consumers as a type of Destination factory production type message consumer or producer; if Destination Type is TopicSession, it will create for Topic producers and consumers).
  Session may be transacted or may not be transactional, usually, you can pass a Boolean parameters to create the appropriate method on the Connection to set this up. Similarly, you can also transfer to the Session Connection method for creating a parameter, the method can set the message acknowledgment mode Session will be created, and the model will be specified by the client or to confirm any information it retrieved by the consumer ( If a transaction mechanism, this parameter is ignored). Other methods of Session provide a variety of message creation methods that allow you to create specific types of JMS messages containing text, bytes, attributes, and even serialized Java objects (for more information on the following Message Interface). Figure 1 is a graph of the relationship between inheritance and create actual JMS interfaces, see the code in Listing 1.

(N map)

Destination (Destination)
  before creating any producer or consumer news, there must be a specific Destination, through which you can link any producers and consumers. Remember, Destination is a managed object, similar ConnectionFactories. This means that the Destination by WebLogic maintenance, must look to retrieve it via JNDI. It also means that, in this case, Destination must be defined in advance. This does not mean that you always want to create a Destination in advance. JMS API provides the ability to create a temporary Destination, but this can only be created Destination its life cycle Session in use, JMS API can also create permanent Destination at runtime. However, in the current WebLogic JMS implementation, it should be noted that, if you create a Destination by Session, as long as the WebLogic server is running, the Destination will exist. If a server failure or crash, then Destination will not exist. The real way to create a permanent Destination is to create it in weblogic.properties file (See "install.txt" documents to get detailed information on how to do this).
  For the purposes of this article, by our Destination weblogic.properties file is created in advance. Destination defined in this file is created when the WebLogic application server boot, and can be used by client code JNDI. Listing 1 shows the code Send.java file, shows how to create QueueConnection and QueueSession, as well as how to retrieve the package hierarchy as Sender application retrieves Destination, name of the queue we defined in weblogic.properties file as "jdj .article.queue.sender ".

Producers and consumers of news and messages
  the last stage of JMS initialization process is to create MessageConsumers and MessageProducers. Like ConnectionFactory, as they also have two basic interface Connection and Session, in order to use Topic or Queue, there are two basic interface-specific extensions to the basic interface of the Destination. (I use that term in use Producer MessageProducer, Consumer use this term when used MessageConsumer). MessageConsumers retrieved message for transmission to the Destination, MessageProducers for transmitting a message to the Destination. Both created by the Session instance. MessageProducer extended by a specific Destination interface QueueSender and TopicPublisher. MessageConsumer by QueueReceiver and TopicSubscriber interface expansion.
  Once you have created your own MessageConsumer and / or MessageProducer, will make all the preparations to receive and / or send a message. Since producers and consumers to create a Queue or Topic-specific, so I will discuss specific Destination types of these two types of treatment-related in the following sections.

News
  Before entering the next step and begin sending and receiving depth discussion Topic and Queue messages, we need to discuss another interface, that Message, which represents the JMS message itself. This object contains the information sent to the Destination, as well as being Destination listening on information received by consumers. Message instance is created by the session, it consists of three parts: a header, message properties, and body. Header is used to identify and route the message, the client usually does not see or developer processing message header information. Attributes supported by the message transfer values specific to the application. These properties are predefined fields, a complete description of them can be found in the JMS documentation. I will use some of the properties in the sample code. Body part of the message is the actual "payload" message, which has five types, they may be represented by a specific interface 5: StreamMessage, MapMessage, ObjectMessage, TextMessage and BytesMessage (see FIG. 1).

Persistence
  is also an important aspect worth discussing JMS: It supports persistent delivery of the message. Very simple, which means that when a message is sent to the Destination, if the Consumer is not running or is not available, then the message will be saved until the next Consumer connect up to Destination. For example, if you have five applications to listen on a particular Topic, one crash, then the next time the application is started and connected to this particular Topic, despite the application crashes, but sent to this Topic All messages will be sent to the application when the application starts listening again. If this seems difficult to understand, it will make more sense when you run the sample code.

Queue
  Queue for "point" or "one" messaging designed. This means that there should be only one client sends a message to the Queue, and only one application can handle this Queue messages.
In fact, you can have multiple clients to one Queue to send a message, but only one application handles the Queue messages. If you have more on the Consumer Queue, then the message will be received by the Consumer which can not be guaranteed, but only one message is received by the Consumer. If more than on Consumer Destination, and they want to receive the same message, Topic should be used (see later below herein).
  Sender.java and Receiver.java file contains code that shows how to use Queue. The code shows the initialization process JMS, and shows how to retrieve pre-defined Queue, and to send and receive messages on Queue, and how to create MessageProducer MessageConsumer.
  And generating a message to the consumer in the Queue, the system has two specific interfaces. Wherein a is the QueueSender interfaces, by calling it a createQueueSender QueueSession () method returns from the QueueSession, for sending a message to the Queue. Another is the QueueReceiver the interface, which is () method that returns from the QueueSession, for receiving a message from a Queue by calling the createQueueReceiver QueueSession.
  Listing 2 is the code from Sender.java of sendMsg method, which shows how to how to create MessageProducer from Session, and then construct a TextMessage and send it. In this code, we will create a QueueSender, and then create a TextMessage, which contains TextField retrieved from the application user interface to the text. Then, we use the method QueueSender "send" messages.
  On MessageConsumer, there are two methods for processing incoming messages received: synchronous and asynchronous. The first step is to create MessageConsumer; the next step is to determine if you want to send synchronous or asynchronous message send a message on the Consumer.
  After creating MessageConsumer from the Session, if you want to sync to receive the next message Destination generated, then the method can be retrieved on MessageConsumer call. This method does not take any parameter, before a Message at the reception, it has been blocked, and the Message will be returned to the caller. In order to receive asynchronous messages, you can register to implement a MessageListener interface MessageConsumer. This method applies to Topic and Queue. MessageListener only one method that you must implement - onMessage, it only takes one argument, namely Message. When a message is sent to the Destination onMessage implemented for each, it invokes the method. Sender.java and onMessage achieve Receiver.java in the demonstration of this process. In Receiver.java, we will put the following code initializeJMS method, this code will create MessageConsumer (a QueueReceiver) and set the realization of MessageListener:

// at The Queue for the Create A Receiver ...
Receiver = session.createReceiver ( Queue);
// the Set at The listener (the this class)
receiver.setMessageListener (the this);

  Once called the Connection start method, the message will be in the arrival Destination entered the Consumer.

ReplyTo-- use temporary queue
  You will also notice, Sender.java and Receiver.java have achieved MessageConsumers and MessageProducers. Both have achieved MessageListener. This illustrates an interesting feature of JMS, that is, it uses temporary Destination. It wishes to receive information generated in response to the application can create a temporary Queue or Topic, and pass in the Destination Message sent it.
The property is one of Message JMSReplyTo property. This property is used for this purpose. You can create a temporary Queue or Topic, and put it into the Message of JMSReplyTo property. Consumers receive the message a private, temporary Destination, you can use it to respond to the sender. There are two ways that this can be explained, these two methods were in both files. Sender.java contains snippet shown below, it will create a temporary Queue, and place it in the TextMessage JMSReplyTo properties:

// Temporary Queue for the Create A replies Number ...
tempQueue = (Queue) session.createTemporaryQueue () ;

  above this line of code can be found in the Sender.java initializeJMS method. This code will create a temporary Queue when you start the application, and this Queue will exist in the entire life cycle of the application. This line of code can be found in sendMsg method Sender.java in, it shows how to set JMSReplyTo property to include a temporary Queue.

Temporary Queue to the Set the ReplyTo // ...
msg.setJMSReplyTo (tempQueue);

  Upon receipt of this message in the QueueReceiver Receiver.java, extracts from the temporary JMSReplyTo Queue field, and constructs a QueueSender by application to the response message back Sender.java. This demonstrates how to use the JMS Message properties, and shows the usefulness of private temporary Destination. It also shows how you can both client Producer message, there is a Consumer messages. The following code from Receiver.java, it shows how to extract from the temporary JMS Message Queue; the code can be found in onMessage method:

// The Temporary the Get Queue from the JMSReplyTo The
// Property of ... The Message
tempQueue = ( Queue) msg.getJMSReplyTo ();

  the following code block from sendReplyToMsg method that shows how to create and how to send a response QueueSender:

// Create a Sender for Queue the Temporary
IF (SENDER == null)
SENDER = session.createSender (tempQueue) ;
TextMessage session.createTextMessage MSG = ();
msg.setText (REPLYTO_TEXT);
...
To the Send the Message at The at The // the Temporary Queue ...
sender.send (msg);

topic
  Topic is to achieve "publish / subscribe" message delivery mechanisms and design. And in order to have a Queue is a Producer and Consumer designed, Topic design goal is allowed to have a plurality of messages can be sent to it Producer, also have to receive the same message from a plurality of Consumer Topic.
  Queue creation process is similar to the Topic of the MessageProducers and MessageConsumers. You can use Session to create TopicPublishers and TopicSubscribers. QueueSender exists and QueueReceiver mirror, because they provide a Topic-specific functions, and have achieved a basic MessageProducer and MessageConsumer interface.
  TopicPublisher creation process is nearly identical to the creation of QueueSender. The following code sendMsg from Publisher.java method, which shows the creation process TopicPublisher, and how to publish a message Topic:

// the Create A Publisher IF there IS not One ...
IF (Publisher == null)
Publisher = the session. the createPublisher (Topic);
TextMessage session.createTextMessage MSG = ();
msg.setText (text);
...
Publish to IT at The Topic // ...
publisher.publish (msg);

durable subscribers
  TopicSubscribers One interesting aspect is that it's durable subscribers, that is, to provide users with a unique name, you can recognize this name in the Session. Session has associated with a Client ID, this ID is either defined at run time by calling a method on the Connection, either as part of a managed ConnectionFactory (in our example, it is used in the file weblogic.properties defined in this way). Thus, a Session Connection may be provided with a Client ID, and name of the durable subscriber unique identifier is the Session, it is associated with a particular Client ID. Durable subscribers purpose is to create a unique, durable Consumer for a given Topic.
  By creating TopicSubscriber application calls the TopicSession createDurableSubscriber method must pass a durable subscriber's name (a string) as one of its parameters; for example, you can subscribe to a lasting name of the user who is currently logged in to the name of, and many more. This name uniquely identifies a particular subscriber of a Topic (along with the Connection / Session of unique Client ID). Once you have registered this durable subscribers to Topic, the Topic will ensure persistent message is sent to the subscribers there. This means that if a particular durable subscriber is unavailable, it will have been saved messages until the next time this durable subscribers (with the same, the only durable subscriber name and Client ID) so far registered as a Consumer . Subscriber.java file shows the process of creating durable subscribers, and allows you to use the default name of the subscriber, or set the identifier from the command line (to get on to run the application and get the message through display durable subscribers have permanent For more details, please refer to the "readme.txt"). The following code fragment from Subscriber.java of initializeJMS method, which shows how to create a durable subscription from TopicSession in person:

up for Subscriber = session.createDurableSubscriber (
Topic,
subscriberID,
SELECTOR,
false);
// the Set at The listener (the this class)
up for Subscriber. setMessageListener (the this);

  TopicSubscribers has not been created for durable subscribers, so it does not receive messages persistently, but only to receive a message during operation.
  To obtain information about durable subscribers and Topic of further, please refer to Sun's JMS documentation. Another point of the above code is: Note that the third parameter passed to the method, this parameter is SELECTOR. This is the message selector associated with Consumer place (see the following content to get more information about the message selector).

Filter - Use message selector
  last aspect we will discuss about the JMS message is selected, a message selector for MessageConsumers filter properties and can be used to filter incoming message header portion (but not filter message body), and determines whether to actually consume the message. JMS document according to statement, the message selector is some string, which based on a grammar, syntax and this is a subset of SQL-92. You can choose the message as part of MessageConsumer created. The MessageConsumer is QueueReceiver or TopicSubscriber, this method is applied to the selected message will be slightly different incoming information. I recommend that you check Subscriber.java file and run the Publisher and Subscriber applications, check the message collector of grammar, and see how to apply them. The following code segment in Subscriber.java in the message selector, and the application itself allows you to change the selection from the text field:

public String SELECTOR = Final "the JMSType = 'TOPIC_PUBLISHER'";

  the selector examined from a Topic incoming JMSType properties of the message, and determine the value of this property is equal to TOPIC_PUBLISHER. If they are equal, the message is delivered to the MessageListener achieve; if not equal, then the message will be ignored. See the "readme.txt" file for more details about running these applications and demonstrate its behavior. It is also recommended that you refer to Sun's JMS documentation.

Conclusion
  JMS is a portable messaging created in the application code delivered attractive, and powerful technology. It allows for "point to point" and "publish / subscribe" messaging, but also supports the transaction and persistence. BEA's WebLogic application server provides a robust and complete implementation of JMS, and other technologies can work together to provide application server, such as EJB and servlet. This message is permanent, asynchronous transaction support by objects between different companies and service delivery to create a great possibility. I hope this article will encourage you to develop online sample code, and can encourage you to check the possibility of WebLogic (especially JMS) provides.

ORIGINAL
http://www.sys-con.com/story/?storyid=42639&de=1

Reproduced in: https: //www.cnblogs.com/kapok/archive/2005/10/15/255324.html

Guess you like

Origin blog.csdn.net/weixin_30932215/article/details/94783370