Chapter 4 Application WebLogic JMS Service
Researcher: Teng Yong
Documentation Description: This document describes the EJB JMS implementation mechanism and how to configure JMS services in WebLogic.
In distributed enterprise applications, asynchronous message mechanism is used to effectively coordinate the work of each part. J2EE provides us with JMS and message-driven beans (Message-Driven Beans) to implement asynchronous messaging between applications.
First, what is a message system?
Typically a message system allows reliability communication between unpacked applications. In an enterprise application, there is a need for asynchronous, non-blocking messaging. For example, a client may wish to send a request to a request, do not care about whether it will receive it immediately. In this way, the client has no reason to wait for the server to process the request. After the client application is submitted, you can handle other tasks with just make sure that the request is requested to reach the server. Usually, this is very efficient. The message system provides the advantages of many other distributed object computing models. It encourages "loose coupling" between message generator and users, with a high degree of transaction between them. For the user, it does not care when to generate a message, whether the generator is still in the network and when the message is generated. This allows for establishing a dynamic, reliable and flexible system. The entire subsystem can be modified without affecting the rest of the system.
Additionally, the high degree of scalability of the system is easy to integrate with other systems, as well as high reliability. Due to reliability and scalability, they are used to solve many business and scientific calculations. For example, the message system is the basis of many applications, which can be workflow, network management, communication service, or supply chain management program. In Java technology, the ability to process asynchronous messages is implemented by JMS. JMS initially designed to provide a standard Java interface to the traditional message object middleware. These products must be in an enterprise application. There are now many products that support JMS's pure Java.
Message systems typically have two messages.
1, Publish / Subscribe (Publish / Subscribe)
The publish / subscription message system supports an event-driven model, message generator, and user participating in the message. Generator publishing an event, while the user subscribes to the incident of interest and uses an event. Generator will connect messages and a specific topic (Topic), and the message system transmits the message to the user according to the interest of the user registered.
(Publish / Subscribe (Pub / Sub) Messaging
2, point-to-peer "
In the point-to-point message system, the message is distributed to a separate user. It maintains an "enter" message queue. Message application sends a message to a specific queue, and the client gets a message from a queue.
(Point-to-Point (PTP) Messaging
Second, JMS introduction
JMS is an enterprise-class message system, also known as a message-oriented middleware. It allows applications to communicate via messaging. A message can be a request, one report, or (or) is an event, which contains information required to coordinate communication between different applications. The message provides an abstract level that allows you to separate the details of the target system from the application code. Java Message Services is a standard API access to an enterprise-level message system. Detailed, JMS:
l Authorized Java applications share a messaging system for message communication.
l Provide a set of standard interfaces to create, send and receive messages, simplify applications development.
Here is a diagram of WebLogic JMS communication.
(WebLogic JMS Communication) As shown, WebLogic JMS receives messages from the message producer application and passes the message to the message consumer application.
Below is a diagram of the WebLogic JMS architecture:
(WebLogic JMS architecture)
1, JMS object model
The following figure shows the JMS object to provide an object that the JMS client is connected to the JMS service provider.
(JMS object model)
ConnectionFactory is a client to create a Connection management object. This object is relatively large because there is an authorization and communication establishment process when CONNECTION is created.
The Destination object packages the purpose of the message and the address and configuration information related to the service provider.
Session is a JMS entity to support transaction processing and asynchronous messaging. JMS does not require the client's code for asynchronous messages or can handle multiple concurrent messages. Typically, the complexity of the transaction is packaged by a session. A session is an atomic unit work, like a transaction of the database, is difficult to implement multithreaded transactions. Session provides the advantage of concurrent in a thread programming mode.
MessageProducer and MessageConsuMer objects are created by the Session object. Used to send and accept messages. To ensure that the message is passed, the JMS service provider processed the message to be in the Persistent mode. The Persistent mode allows the JMS provider to save the message.
(Session, MessageProducer and MessageConsumer are not supported, and ConnectionFactory, Destination, and Connection support concurrent.)
2, JMS application development
In the JMS message system, the key to communication between applications is that messages. So using JMS must first understand the message. In JMS, the message consists of three parts:
Message header is used to identify messages, such as whether a given message is a "subscriber"
Properties is used to be related to applications, providing information related and optional information
Body is the content of the message, supports several formats, including TextMessage (a simple package for String) and ObjectMessage (package of any object, but must support serialization), and other formats.
N TextMessage
A TextMessage is a package of String objects. It is useful when only text objects are passed. It assumes that many messages are built on XML. Thus TextMessage can be a container that packs them.
Creating a TextMessage object is simple, as follows:
TextMessage Message = session.createMessage ();
Message.Settext ("Hello, World!");
N ObjectMessage
As shown in the name, it is a message for a package of a Java object. Any serialized Java object can be used for ObjectMessage, and if multiple objects can be packaged in one message, you can use the Collection object to include multiple serialized objects.
Here is to create an ObjectMessage
ObjectMessage Message = session.createObjectMessage ();
Message.SetObject (MyObject); create a JMS client program
A typical JMS client is created by several basic steps below:
n Create a connection to the message system provider (Connection)
n Create a session for receiving and sending messages
n Create MessageProducer and MessageConsumer to create and receive messages
When the above steps are completed, a message generator client will create and publish a message to a topic, and the message user client receives a message related to one topic.
1 Create a Connection
A Connection provides access to the client to the underlying message system. And achieve resource allocation and management. Create a Connection by using a ConnectionFactory, usually specified by JDNI:
Connection Message = New InitialContext ();
TopicConnectionFactory TopicConnectionFactory = (TopicConnectionFactory);
Topic = (TOPIC) JNDICONTEXT.LOOKUP (TopicName);
TopicConnection = TopicConnectionFactory.createtopicConnection ();
2 Create a session
Session is a relatively large JMS object that provides a means of production and consumption messages. Used to create a message user and message generator.
TopicSession = TopicConnection.createtopicSession (false, session.auto_acknowledge);
Two parameters are used to control transactions and messages confirmation.
3 positioning a Topic
Use JDNI to locate a Topic, TOPIC is used to identify messages sent or received, in the publish / subscription system. Subscribe subscribe to a given Topic, and the publisher will be connected to a Topic.
Here is to create a Topic "WeatherReport"
Topic Weathertopic = Messaging.lookup ("WeatherReport");
4 launching the Connection
After the above initialization step, the message flow is prohibited, and it is for preventing unpredictable behavior during initialization. Once the initialization ends, the Connection will be enabled to start the message system.
TopicConnection.Start ();
5 Create a message generator
In the release / subscription, a generator issued a message to a specified Topic. The following code shows creates a generator, as well as subsequent establishment and releases a simple text message.
TopicPublisher Publisher = session.createpublisher (WeatherTopic);
TexeMessage Message = session.createMessage ();
Message.setText ("SSSS");
Publisher.publish (Message);
Below is a message user code
TopicConnection = TopicConnectionFactory.createtopicConnection ();
TopicSession = TopicConnection.createtopicSession (false, session.auto_acknowledge);
TopicsUbscriber = Topics; Topic; TopicListener = new msglistener (); TopicsUbscriber.SetMessageListener; TopicConnection.Start ();
Third, message driver bean profile
Asynchronous messages can also be implemented by the message driver bean. In the EJB1.1 specification, two types of EJB are defined. They are entity bean (EntityBean) and session beans (sessionbean). The client is usually a method of calling the bean in synchronous, blocked mode. The message driver bean combines the functionality of EJB and JMS.
As mentioned above, session beans typically implement business logic, and clients cannot share a session bean. Entity beans are typically corresponding to some of some entity entries in permanent storage. Both beans usually have a Remote and Home interfaces for interacting with the client. Also, these interactions are synchronized, blocked. For example, a request is sent to a bean, and the server returns a corresponding corresponding to the blocking method. The caller can proceed to the next step after receiving the return. Message Driver Bean is typically configured to be a special topic (TOPIC) or a queue client, as a user of the message. But the message driver bean does not have a Home and Remote interface. When a message generator writes a message to Topic or queue, it does not know that the user is a message-driven bean. This allows integrated distributed computing systems, there is a lot of flexibility. The message driver bean has no state of the session property, and all instances are the same when the request is not processed, which is similar to the stateless session bean. Place the instance of the bean in the buffer pool and a method of efficient processing message-driven beans. A message drive bean must be inherited from the Javax.ejb.MessageDriveNbean interface indirectly or directly. This interface is inherited by javax.jms.MessageListener. One parameter of this method is javax.jms.Message. Can be any effective JMS message type. A THROWN statement does not include a statement of the method. Therefore, in the message processing, it will not still be abnormal. When the container receives a message, it is first to get a ready-made message from a buffer pool, and then if the configuration file is required, the container also sets a connection with the transaction context. When these management tasks are completed, the received messages are delivered to the onMessage () method. Once the method is completed, the transaction is confirmed or returned, the bean is resended back to the buffer pool.
Ejbremove () calls when the message driver bean is deleted from any storage. And make clear operations and garbage collection. The resources for all Beans's instances must be released in the EJBREMOVE () method.
The setMessageDrivenConnection () method has only one parameter -Javax.ejb.MessageDrivenContext instance. The MessageDrivenContext class is similar to the context in the entity and session bean. When an instance of a bean is created, the container is incorporated into the context used by bean. The method of obtaining environmental information in the context, and the JTA UserTranscation class, which is used for Bean management transaction.
In addition, the bean provider must provide an ejbcreate () method (no parameters) for setting the bean on the EJB server. Bean instances can achieve any resources required in the EJBCREATE () method.
The message driver bean greatly simplifies creates a JMS user, creates and configures a JMS message user, which is made to the EJB container. Developers simply implement the message-driven interface interface, configure it to the EJB server to create a business logic component that receives a message. Fourth, a JMS application instance (code from the test item)
Function description
Customers in an e-commerce website If you decide to buy a item, you will enter the "ShowquoteServlet.java" page (ShowquoteServlet.java), click on the "Submit Order" button, this action will call
(place an order)
The purchase () method of CartBean.java (shopping basket object), which will instantiate a order object (ORDER) in this method, generate an Order ID, and then pass the Order ID through the SendMessage () method (ie Messagesender.java class) The same name method) is sent to the JMS server as a "order processing" message, then the "Order ProcessorBean.java" message driver bean is accepted, and the logo field of the order is set to "Approved" after processing the transfer account. Thus completing a transaction. Customers will see the following success information:
(Successful purchase)
Code
1, "Show Shopping Basket Product" page (showquoteservlet.java)
...
/ *
* If the customer click on the "Submit Order" button
* /
IF (Request.GetParameter ("Order")! = null) {
/ *
* Transform the shopping basket to orders, complete payment function (application JMS)
* /
String ORDERID = Cart.purchase ();
/ *
* Add ORDERID into the request to get the JSP to get
* /
Request.setttribute ("ORDERID", ORDERID;
/ *
* Clear the shopping basket so that customers can purchase to continue shopping
* /
Cart.clear ();
/ *
* Steering success page
* /
THIS.GetServletContext (). getRequestDispatcher ("/ receipt.jsp"). Forward (Request, Response);
Return;
}
...
2. Purchase () method and sendMessage () method for CartBean.java (shopping basket object)
...
/ **
* Buy goods in the shopping basket.
Shopping basket objects will create one in the database
* Order.
*
* @ Return Order ID
* /
Public string purchase () {
Try {
/ *
* Lock the ORDER HOME object
* /
OrderHome Home = getorderHome ();
/ *
* Create ORDER
* /
String ORDERID = MakeUniqueId ();
Order Order = Home.create (ORDERID, Owner, "Unverified", Subtotal, Taxes;
/ *
* Create ORDERLINEITEMS (order product list) object
* /
Vector OrderItems = AdorderLineItems (Order); / *
* Deposit ORDERLINEITEMS into Order
* /
Order.setLineItems (OrderItems);
/ *
* Send JMS messages to Topic
* /
SendMessage (ORDERID);
/ *
* Return to Order ID
* /
Return OrderId;
} catch (exception e) {
Throw new ejbexception (e);
}
}
/ *
*
* Send JMS messages to Topic
* @ param jms message, here is ORDERID
* /
Private void sendmessage (string message) throws exception {
Try {
Messagesender sender = new messagesender ();
Sender.sendMessage (MESSAGE);
} catch (exception ex) {
Throw EX;
}
}
...
3, Messagesender.java class
Package examples;
Import java.io. *;
Import java.util. *;
Import javax.transaction. *;
Import javax.naming. *;
Import javax.jms. *;
/ *
*
* This class sends JMS text message to topic
* /
Public class message messagesender {
/ *
* Define JNDI CONTEXT FACTORY.
* /
Public final static string jndi_factory = "WebLogic.jndi.wlinitialContextFactory";
/ *
* Define the JMS Connection Factory JNDI name.
* /
Public final static string jms_factory = "jasmine.examples.jms.topicConnectionFactory";
/ *
* Define the JMS Topic JNDI name.
* /
Public final static string Topic = "jasmine.examples.jms.orderprocess";
/ *
* Define the Server URL
* /
Public final static string url = "t3: // localhost: 7001";
/ *
* Define JMS Connection Factory
* /
Protected TopicConnectionFactory TCONFACTORY;
/ *
* Define JMS Topic Connection
* /
Protected TopicConnection TCON;
/ *
* Define JMS Topic Session
* /
Protected TopicSession TSession;
/ *
* Define JMS Topic Publisher
* /
Protected topicpublisher tpublisher;
/ *
* Define JMS Topic
* /
Protected topic Topic;
/ *
* Define JMS TextMessage
* /
Protected textMessage MSG;
/ *
*
* To send Messages to a JMS Topic
* Create all necessary objects.
*
* @Param CTX JNDI Initial Context
* @Param TopicName Name of topic
* @Exception namingexcpection if problem @ @Exception jmsexception if jms fails to initialize due to in Security Error
*
* /
Public void init (Context CTX, String TopicName)
THROWS NAMINGEXCEPTION, JMSEXCEPTION {
/ *
* Lock Topic Connection Factory JNDI
* /
TconFactory = (TopicConnectionFactory) CTX.lookup (JMS_Factory);
/ *
* Create a Topic Connection Factory
* /
TCON = tconFactory.createtopicConnection ();
/ *
* Create a Topic Session
* /
Tsession = tcon.createtopicSession (false, session.auto_acknowledge);
/ **
* Lock Topic JNDI
* /
Topic = (TOPIC) CTX.lookup (TopicName);
/ **
* Create a Publisher
* /
Tpublisher = tession .createpublisher (Topic);
/ **
* Create TextMessage
* /
Msg = tession.createtextMessage ();
Tcon.Start ();
}
/ **
* Create all the necessary JMS objects to send a Message to a JMS Topic.
* @Params Message Message to Be Sent
* @Exception jmsexception if jms fails to send message Due to Internal Error
*
* /
Public void sendmessage (string message) throws jmsexception {
Try {
InitialContext CTX = GetInitialContext (URL);
INIT (CTX, Topic);
Send (Message);
} catch (exception ex) {
Throw new jmsexception (ex.getMessage ());
} finally {
CLOSE ();
}
}
/ **
* Send a Message to a JMS Topic.
*
* @Params Message Message to Be Sent
* /
Public void send (String Value)
Throws jmsexception {
Msg.settext (value);
TPublisher.Publish (MSG);
}
/ **
* Close the JMS object.
*
* @Exception jmsexception if jms fails to close objects Due to Internal Error
* /
Public void close ()
Throws jmsexception {
Tpublisher.close ();
Tsession.close ();
Tcon.close ();
}
/ **
* Return to the application server to initialize the environment context information.
* /
Protected Static InitialContext GetInitialContext (String URL)
Throws namingexception {
Hashtable env = new hashtable (); env.put (context.initial_context_factory, jndi_factory);
Env.put (Context.Provider_URL, URL);
Env.put ("WebLogic.jndi.createInterMediateContexts", "True");
Return New InitialContext (ENV);
}
/ **
* main () method. Used to test this class.
*
* @Param Args WebLogic Server URL
* @Exception Exception if Operation Fails
* /
Public static void main (string [] args)
Throws exception {
IF (args.length! = 1) {
System.out.println ("USAGE: Java Examples.jms.topic.topicsend WebLogicURL");
Return;
}
InitialContext IC = GetInitialContext (Args [0]);
Messagesender sender = new messagesender ();
Sender.init (IC, TOPIC);
Sender.send ("123456");
Sender.close ();
}
}
4, "Order ProcessorBean.java) Message Drive Bean
Package Example; import javax.ejb. *;
Import javax.jms. *;
Import javax.naming. *;
Import javax.rmi.portableremoteObject;
/ **
* This message drive (Message-Driven) bean accepts JMS Messages
* To implement the purchase process. ORDER Processing will be executed.
* /
Public Class OrderProcessorBean Implements MessageDriveNbean, Messagelistener {
Protected MessageDrivenContext CTX;
/ **
* This is a business approach owned by Message-Driven Beans.
* In this we perform real order processing
* /
Public void OnMessage (Message MSG) {
TextMessage TM = (TextMessage) MSG;
Try {
String ORDERID = Tm.getText ();
Context ctx = new initialContext ();
ORDERHOME HOME = (ORDERHOME)
PortableRemoteObject.narrow
CTX.lookup ("ORDERHOME"), ORDERHOME.CLASS;
Order Order = Home.FindByPrimaryKey (ORDERID);
/ *
* Here we can do other tasks:
*
* - Check the user's credit card CREDIT and perform the skip operation.
*
* - Check the stock to ensure that the item can be sold.
*
* - Check information about delivery.
*
* - Send Email Certification Information
*
* In this case, we will only change the STATUS of the ORDER to
* "approved".
* /
Order.setStatus ("approved");
}
Catch (Exception E) {
E.PrintStackTrace ();
Throw new ejbexception (e);
}
}
/ **
* Make the bean instance contact with a special context.
* We can query environment information in this Context.
* /
Public void setMessageDrivenContext (MessageDrivenContext CTX) {
THIS.CTX = CTX;
}
/ **
* Initial server Container in the lifecycle will call this method.
* We will do some initialization work.
* /
Public void ejbcreate () {
System.err.println ("ejbcreate ()");
}
/ **
* Server Container calls this method to clear the bean.
* /
Public void ejbremove () {
System.err.println ("ejbremove ()");
}
}
5, "Order ProcessorBean.java) message Driver BEAN configuration file code
1 ejb-jar.xml
...
ORDERPROCESSOR
Examples.OrderProcessorbean
Container
Javax.jms.topic
...
...
2 WebLogic-ejb-jar.xml
...
ORDERPROCESSOR
100
10
Jasmine.examples.jms.orderprocess
ORDERPROCESSORBEAN
...
5. Configure JMS services in WebLogic 7
Create a JMS dedicated JDBC Connection Pool *
By default, WebLogic's JMS service supports the following databases:
N PointBase
N Microsoft SQL (MSSQL) Server
n oracle
n Sybase
N Cloudscape
N informix
N IBM DB2
N Times Ten
In this example, Microsoft SQL (MSSQL) Server as an example. Create an empty database "JMSDB".
1 Start the server. Open IE, type in the address bar:
2 Enter your username and password
3 Select Services-> JDBC-> Connection Pools in the directory tree on the left, click the Configure a new jdbc connection pool on the right. Enter the following information:
Configuration-> General Page:
Name = JMS JDBC POL
URL = JDBC: WebLogic: MSSQLSERVER4: JMSDB @ localhost
Driver classname = WebLogic.jdbc.msqlserVer4.driver
Properties: User = SA
Password = <- sa password (this example is empty)
Click Create to establish a connection pool.
Targets-> Server Page: Move the TY (server name) to the list of the right, but click Apply.
(* Note: JMS service cannot share a connection pool with your EJB components, otherwise it will fail when publishing the EJB component.)
Create a JDBC Store (for a long-lasting Messages in the database)
1 Click JMS -> Stores tag, then click "Configure a new jmsjdbcstore" in the right panel. Create a new JMSJDBCStore. 2 Fill in the name and select the data connection pool.
3 After the creation is successful, the Store will appear on the left.
Create JMS Template (to define different Destinations for similar properties settings)
1 Click the templates option on the left panel, then click Configure A New JMS Template on the right panel.
2 In the General page, fill in the Template name and click "CREATE".
3 Thresholds & quotas, Override and RedLivery Select the default value.
Configuring JMS Server
1 Click the JMS Server option on the left panel and click Configure A New JMSServer on the right panel.
2 In the General page, fill in the name, select a Store, select a Paging Store, select a template, then click "CREATE".
3 Thresholds & quotas Select the default value.
4 In the Targets panel, select Application Server "TY" from the drop-down list, click "Apply".
Create JMS Destinations, Queues (Point-To-Point) or Topics (Pub / Sub), this example is Topics
1 Click on the DESTINATIONS under the JMS Server option under the left panel, then "Configure a new jmstopic" on the right panel.
2 In the General page, fill in the name, JNDI name and other options and click "CREATE".
3 Thresholds & quotas, Override, RedElivery, and Multicast (Topics Only) Select the default value. After the creation is complete, as shown in the figure -
Create Connection Factory (so that the client can establish JMS connection)
1 Click the JMS Connection Factory option on the left panel, then click Configure A New JMS Connection Factory on the right panel.
2 In the General page, fill in the name jasmine.examples.jms.topicconnectionFactory, JNDI name JASMINE.EXAMPLES.JMS.TOPICCONNECTIONFACTORY, Other options are default, and then click "CREATE".
3 In the Targets panel, select Application Server "TY", click "Apply". -
At this point, the JMS service configuration is basically completed. If you view the JMSDB database, it will find that WebLogic has established two tables for storing JMS data.
(MS SQL Server Database)