Message Driven Beans Tutorial (new EJB type, absolutely wonderful !!!!!)

zhaozj2021-02-11  221

The following tutorial illustrates how a Message Driven Bean is written and deployed in an Enterprise JavaBeansTM 2.0 Container. The MDB component is invoked by an inbound message from a Java client. This function is demonstrated with a sample application run on Pramati Server 3.0 (Alpha) . The Server ships with Pramati Message Server 1.0 and can be downloaded from www.pramati.com. The application sources are freely downloadable to get a better understanding of how MDB components are written and work. What is a Message Driven Bean? A message driven bean is a stateless, server-side, transaction-aware component that is driven by a Java message (javax.jms.message). It is invoked by the EJB Container when a message is received from a JMS Queue or Topic. It acts as a simple message listener. A Java client, an enterprise bean, a Java ServerPagesTM (JSP) component, or a non-J2EE application may send the message. The client sending the message to the destination need not be aware of the MDBs d eployed in the EJB Container. However, the message must conform to JMS specifications. Before MDBs were introduced, JMS described a classical approach to implement asynchronous method invocation. The approach used an external Java program that acted as the listener, and on receiving a message , Invoked a session bean method. HOWEVER, INTIS Approach The Message Was Received Outside The Application Server and Was Thus Not Part of a Transaction In The EJB Server. MDB Solves this qu.

Message Processing Before (Above) Andreat (BELOW) MersSage Driven Beans.

Structure of an MDB

It has no home or remote interfaces, and is only a bean class It resembles a stateless session bean -.. That is, it has short-lived instances and does not retain state for a client A client interacts with the MDB in the same way it interacts with a JMS application or JMS server. Through the MDB, the EJB 2.0 Container sets itself up as a listener for asynchronous invocation and directly invokes the bean (no interfaces), which then behaves like an enterprise bean. All instances of a particular MDB type are equivalent as they are not directly visible to the client and maintain no conversational state. This means that the Container can pool instances to enhance scalability. Lifecycle of an MDB The EJB Container performs several tasks at the beginning of the life cycle of the MDB: Creates a message consumer (a QueueReceiver or TopicSubscriber) to receive the messages Associates the bean with a destination and connection factory at deployment Registers the message listener and the message ac knowledgement mode The lifecycle of an MDB depends on the lifespan of the EJB Server in which it is deployed. As MDBs are stateless, bean instances are typically pooled by the EJB Server and retrieved by the Container when a message becomes available on the topic or queue Writing an MDB Writing an MDB Involves The Following Tasks:

Implement the javax.ejb.MessageDrivenBean and javax.jms.MessageListener interfaces in the MDB class. Provide an implementation of the business logic inside the onMessage (). Provide a setMessageDrivenContext () method that associates the bean with its environment. Provide an ejbCreate ( ) method that returns void and takes no arguments. This method may be blank. Provide an ejbRemove () method implementation. This method may be blank, unless certain resources need to be acquired before the bean goes out of scope. Sample application The tutorial uses a sample application, StockTrader, to illustrate the writing of an MDB. The sample uses a simple message driven bean buyAgentMDB that is contacted by a client which wishes to buy shares. The client looks up the BuyQueue and implements the javax.jms.MessageListener. IT Provides a private method Buy () Takes Two Arguments: a Double Value That Holds The Price And A String (StockSymbol) That Holds The Scrip symbol.sample application component

ClientStockServer.javaacts as a server and displays fluctuations in stock prices.

DestinationsStockMarketA topic where stock price details are published to StockServerBuyQueueA queue on which BuyAgent MDB listens for stocks under buy adviseSellQueueA queue on which SellAgent MDB listens for stocks under sell advise

Message Driven BeansBuyAgentMDB.javaInvoked by messages received from BuyQueue and in turn updates the topic StockMarketSellAgentMDB.javaInvoked by messages received from SellQueue and in turn updates the topic StockMarketSubscriberBean.javasends client's buy / sell actions to BuyQueue or SellQueue on the message server

Defining The MDB Class AN MDB IMPLEMENTS TWO Interfaces: Javax. . jms.MessageListener and javax.ejb.MessageDrivenBean The MDB class is defined as public and can not be defined as abstract or final The MDB class looks like this:. public class BuyAgentMDBimplements MessageDrivenBean, MessageListener {

Private messagedrivencontext mdbcontext;

The Class Must Const of:

A public constructor with no argument A single onMessage method public void ejbCreate () with no arguments public void ejbRemove () usually used to free resources allocated in ejbCreate method public void setMessageDrivenContext (MessageDrivenContext mdc) called by the EJB Container after the creation of the instance , without any transaction context The class must not contain the finalize method. Implementing business logic Business logic for the EJB is triggered by the onMessage () method of the MDB. The onMessage () is called by the Container when the JMS Queue or Topic receives . a message The onMessage () does not return any result and has one argument The full JMS message object is passed as an argument The signature for the method is:.. public void onMessage (Message msg) {}

In the sample, when there is a message on the BuyQueue, the onMessage () method of the BuyAgent picks up the message and sends it to the topic StockMarket. The StockRepository in turn looks up this topic. The following code of the buyAgentMDB performs this Function: Public void OnMessage (Message MSG) {

// Retrieves the text message

TextMessage PriceMessage = (TextMessage) MSG;

Try {

}

Catch (JMSException EX)

{EX.PrintStackTrace ();

}

}

Implementing the ejbCreate method The ejbCreate () is called at the time of bean instantiation, in order to allocate resources such as connection factories if the bean send messages or datasources, if the bean accesses databases This method is invoked once in the lifecycle -. When THE FOLLOWING CREATED. The Following Code of the Buyagentmdb Performs this function: public void ejbcreate () throws createException {

}

Providing methods for transactional management The setMessageDrivenContext provides the methods for transaction management. The BuyAgentMDB implements setMessageDrivenContext. This method is called by the EJB Container to associate the BuyAgent instance. The context is maintained by the Container. The input parameter for setMessageDrivenContext is an instance of the MessageDrivenContext interface. It gives the MDB access to information about the runtime environment. In Container-managed transactions, de-queuing occurs out of the onMessage (). The only methods on the MessageDrivenContext that are accessible to the MDB are transaction-related methods . Removing the instance This method is invoked when an MDB is being removed from a pool Application server vendors may implement an arbitrary algorithm that decides when to remove the MDB instances from the pool The following code of the BuyAgentMDB performs this function:.. public void ejbremove ()

{

// Removes the bean from the pool

}

Acknowledging messages For MDBs that use container-managed transactions, the Container automatically acknowledges a message when the EJB transaction commits. The Container overrides the acknowledgement mode given in the deployment descriptor. If the EJB uses bean-managed transactions, both the receipt and the acknowledgement of a message occur outside the EJB transaction context. Setting up the response Some business cases may require responding to the Sender of the message that triggered the MDB. to register the "reply to" destination of the Sender, the client can use getJMSReplyTo header. The JMSReplyTo header field contains a destination supplied by the client along with the message. It is the destination where a "reply to the message" may be sent. Messages sent with a JMSReply value typically expect a response. The code to use the JMSReplyTo header Looks like this: public void onmessage (message msg) {try {

Destination d = msg.getjmsreplyto ()

}

Catch (jmsexception jmse) {}}

Deploying the MDB The destination associated with an MDB is specified in the deployment descriptor of the MDB in the ejb-jar.xml file A destination is a JMS-administered object accessible via JNDI Here is a sample destination entry in the deployment descriptor..:

javax.jms.topic

Nondurable

Elements in The Deployment Descriptor The Description of a MDB in The EJB 2.0 Deployment Descriptor Contains The Following Specific Elements:

the JMS acknowledgement mode: auto-acknowledge or dups-ok-acknowledge an eventual JMS message selector: this is a JMS concept which allows the filtering of the messages sent to the destination a message-driven-destination, which contains the destination type (Queue or Topic) and the subscription durability (in case of Topic) The MDB deployment descriptor specifies whether the bean is intended for a Topic or a Queue. A bean set for a Topic can act as a durable subscriber guaranteeing that the listener receives all messages even if the listener is unavailable for some time. The deployment descriptor also sets transaction demarcation and security. If the transaction type is "container", the transactional behavior of MDB methods is defined as for other enterprise beans in the deployment descriptor. Here is the entry For the Transaction Type in The Deployment Descriptor: Container Auto-Acknowledge

For the onMessage method, only the Required or NotSupported transaction attribute must be used as there are no incoming transaction context. The important thing to notice is that the deployment descriptor contains all the information except the destination name required to deploy a message-driven bean. The Destination Name Is Set in An Application Server's Vendor-Specific Configuration File or As a System Property (Deploy Time Mapping).

Running the Sample Configuring The Message Server by Default, The Following Destinations Are Entered In The Configuration File of The Message Server:

BuyQueue SellQueue StockMarket The configuration file is located in the directory [install_dir] /jms/config/jms-config.xml, where [install_dir] is the installation directory of Pramati Server 3.0. Deployment steps The following steps will deploy the application on Pramati Server :.. Start Pramati Server along with the JMS Server Start the Pramati Management Console from the Windows shortcut Unix users must run runadmin.sh from the Server installation directory In the Console, select Server> Start from the main menu This brings up the.. Start Server dialog where the J2EE Server to start is identified Check the Start JMS Server option to start the Message Server along with the J2EE Server This is essential to be able to run the message driven beans Note:... For more details on operating Pramati Server, Refer Online Product Documentation at http://www.pramati.com. Deploying The Application When the Server Starts, Click on The Deploy Button in The View Panel of The Console To Start The Depl Oy Tool. Select Archive> Open and open the application stockapp.ear from the folloading location: [Install_Dir] / Samples / MDB /

WHERE [Install_Dir] is The Installation Directory of Pramati Server 3.0. Deploy the Application. Running The Client Set The ClassPath As Follows:

Windows

Run the file run.bat from the directory

[install_dir] / Samples / MDB

Add The Following Location of the Application Classes to The Client ClassPath:

[Install_Dir] / Server / Samples / MDB / Classes

WHERE

[install_dir] is The Installation Directory of Pramati Server 3.0.

Unix

Export classpath = $ install_root / server / samples / mdb / classes:% $ ClassPath

Starting the stock repository The stock repository is run by the client StockServer.java Start the client by executing:. Java com.pramati.samples.mdb.StockServerThis brings up the stock repository panel which displays the scrip and the price along with a Buy / Sell ​​Advisory Message. Observe the price fluctuates every time Buying or selling happens.

Summary MDBs overcome the limitations of synchronous messaging using session and entity beans in the EJB 1.1 container. MDBs can be deployed in the EJB 2.0 Container, which acts as a message listener and uses inbound messages as a trigger to invoke business methods in an asynchronous manner Tutorial Outlined The Steps Involved in Writing AN MDB Using A Sample Application That May Be Downloaded from www.pramati.com. For further information, contact support@pramati.com.

转载请注明原文地址:https://www.9cbs.com/read-5259.html

New Post(0)