分享
 
 
 

Message Driven Beans Tutorial(新增的EJB类型,绝对精彩!!!!!)

王朝java/jsp·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

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 deployed 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, in this approach the message was received outside the application server and was thus not part of a transaction in the EJB Server. MDB solves this problem.

Message processing before (above) and after (below) Message 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 acknowledgement 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() that takes two arguments: a double value that holds the price and a string (stockSymbol) that holds the scrip symbol.

Sample application components

Client

StockServer.java

Acts as a Server and displays fluctuations in stock prices.

Destinations

StockMarket

A topic where stock price details are published to StockServer

BuyQueue

A queue on which BuyAgent MDB listens for stocks under buy advise

SellQueue

A queue on which SellAgent MDB listens for stocks under sell advise

Message Driven Beans

BuyAgentMDB.java

Invoked by messages received from BuyQueue and in turn updates the topic StockMarket

SellAgentMDB.java

Invoked by messages received from SellQueue and in turn updates the topic StockMarket

SubscriberBean.java

sends client's buy/sell actions to BuyQueue or SellQueue on the message server

<!-- ***************************Continue body text here -->

Defining the MDB Class

An MDB implements two interfaces: javax.jms.MessageListener and javax.ejb.MessageDrivenBean. The MDB class is defined as public and cannot be defined as abstract or final. The MDB class looks like this: public class BuyAgentMDB

implements MessageDrivenBean, MessageListener {

private MessageDrivenContext mdbContext;

The class must consist 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 bean is 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:

<message-driven-destination>

<destination-type>javax.jms.Topic</destination-type>

<subscription-durability>NonDurable</subscription-durability>

</message-driven-destination>

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:

<transaction-type>Container</transaction-type>

<acknowledge-mode>Auto-acknowledge</acknowledge-mode>

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 Deploy Tool.

Select Archive > Open and open the application stockapp.ear from the following 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.StockServer

This 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.

This 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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有