| The New Bean On The Block [Java Technology]
Dated. Jan.2006
Author. Marnie Knue-Merkel :: Sun Certified Java Instructor :: ExitCertified
Summary
So you have written this great application that uses the latest and greatest development ideals. You have properly separated your JSPs from your servlets, EJBs are taking care of the actual work, but the system still gets bogged down. You are really wishing that there was a way to put off processing some of the work until later. Well, I have news for you – with the new EJB 2.0 specification, you can with the help of a new bean called the message-driven bean!
|
|
One of the biggest problems regarding Enterprise Java Beans (EJBs) is that they can take a while to process. Take, for instance, an on-line shopping cart. We would use the JSP to
build the web site. The JSP would quite nicely send the users information to the servlet for initial processing. The servlet would send the information to the EJB for the real processing, the database updating, and then return anything that was necessary to the
servlet so that it could call the appropriate JSP and start the cycle over. The real problem comes with the checkout. EJBs are synchronous, so the client must wait for the transaction to complete and return something before the client can continue. Do we really want the customer to wait for the order to be completely processed and shipped before they can go on to their next thing? Probably not.
Ok, so this is an exaggeration, but I’m sure that you can think of similar processes that
you have in your environment that would fit this problem: some process that don’t have to be done now, maybe it can’t be done now, and you don’t want the client application to
wait for a response. Ta-da! Message-driven beans to the rescue!
Message-driven beans (MDBs) were designed with the idea of using a message service to queue jobs that do not need to be sent back to the client immediately. This provides us several advantages. We can schedule resource intensive jobs for later, when the server is less congested. A particular job can be repeatedly attempted until it is successfully completed. The bean is asynchronous, so the client doesn’t have to wait. The fact that this
is now a part of the EJB 2.0 specification also means that we are now guaranteed to have
a message service of some sort within our application server, and it will support queue
messaging (point-to-point) and topic messaging (publish/subscribe).
When writing an MDB, the client is actually going to be talking to a Message-Oriented
Middleware application. Currently, message-driven beans do this by using the Java
Message Service (JMS) API. The client has no idea that there is a bean, it simply knows whether it is talking to a queue or to a topic within the message service and sets up the appropriate JMS code to talk to the message service. For a simple text message, this might look something like:
QueueConnectionFactory factory = null;
Queue localQueue = null;
try{
InitialContext context = new InitialContext();
factory =
(QueueConnectionFactory)context.lookup(“jms/QueueConnection
Factory”);
localQueue = (Queue)context.lookup(“jms/Queue”);
}
catch(NamingException ne) { }
try{
QueueConnection connection =
factory.createQueueConnection();
QueueSession session =
connection.createQueueSession(true,0);
QueueSender sender = session.createSender(queue);
TextMessage message = session.createTextMessage();
message.setText(“Hello World!”);
sender.send(message);
session.commit();
session.close();
connection.close();
}
catch(JMSException jme) {}
|
|
In this case, most of the code has to do with talking to the JMS service. The most
important lines in regards to our message-driven bean are the two context.lookup
calls. When deploying the bean, both the ConnectionFactory and the Queue JNDI lookup
names will be needed. There are similar method calls for dealing with topic messaging.
The other part that is important is the type of message. There are five message types:
TextMessage, MapMessage, ObjectMessage, StreamMessage, and BytesMessage.
When writing an MDB, the actual coding is much easier than writing any other bean. These beans are very similar to stateless session beans. They are designed to be a service
bean and therefore do not hold any state specific data variables. The biggest difference is
that there are no interfaces to write. We simply write the bean itself. The client, as far as
the MDB is concerned, is the messaging server. The actual user interface never knows
that it is talking to a bean of any type.
When dealing with a Message-Driven bean, we only have four methods that we need to
worry about – ejbRemove(), ejbCreate(), onMessage(Message), and setMessageDrivenContext(MessageDrivenContext). Any other methods
would simply be there to help break up the processes for the onMessage method. If onMessage is successful, then the message service will receive an acknowledgment
that the message was dealt with. The bean also must implement two interfaces: MessageListener and MessageDrivenBean. For example:
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.*;
public class HelloMessageBean implements MessageDrivenBean,
MessageListener
{
private MessageDrivenContext mdc;
public void ejbCreate() {}
public void ejbRemove() {}
public void setMessageDrivenContext(MessageDrivenContext mdc) {
this.mdc = mdc;
}
public void onMessage(Message msg) {
TextMessage message = null;
if(msg instanceof TextMessage) {
message = (TextMessage)msg;
System.out.println(“Message received: “ + message);
}
}
}
|
|
Just as with a stateless session bean, there is only one ejbCreate and it takes no
arguments. ejbRemove is simply designed to de-allocate any instance variables’
memory, such as connections to other beans’ home interfaces. onMessage is the
lifeblood of the MDB. The container is responsible for calling this method, and all of the
responsibilities of any given MDB are coded here. Just as session beans can use either bean-managed transactions or container-managed
transactions, so can message-driven beans. It needs to be noted, though, that MDBs do
not run in the same transaction context as the client. Their transaction can be propagated
to other beans, however. Typically the container-managed transaction is the lifespan of
the onMessage method. During a container-managed transaction, if the transaction rolls back, then no acknowledgment is sent to the messaging service. The messaging service will eventually resend the message. When dealing with a bean-managed transaction, however, the acknowledgment will still occur (unless an exception is thrown) - even if a rollback is performed.
For the best performance, use message-driven beans in place of stateless session beans
when the client doesn’t need an immediate response. The MDB can call any other bean,
plain java class, or even another message service. It simply is designed as a way to
decouple a task from the client to help you, the programmer, increase the efficiency of
your distributed application.
About Marnie Knue-Merkel
Marnie is a Sun Certified Java Instructor and programmer at ExitCertified Corporation.
She combines her superb communication skills, managerial aptitude and technical
knowledge to ensure that students get the most from every topic she teaches. Having
over seven years experience as a professional trainer, Marnie specializes in teaching all
levels of Java enthusiasts all that she knows about the technology.
|
| |
|
About ExitCertified
ExitCertified is an exclusive provider of IT training in North America, authorized by hardware and software vendors including:
Sun Microsystems |
Oracle |
Symantec/Veritas |
IBM |
Project Management |
Magic Draw |
Current facilities are located in Ottawa, Montreal, Vancouver, Calgary, Sacramento, and San Francisco, with training provided globally.
ExitCertified stands for Excellence in IT Certified Education, specializing in advanced fields such as servers and storage, programming, system administration, security, databases and project management.
Our instructors are among the best in North America, having received awards and recognition from our training partners. They are experienced professionals with leading IT certifications and recognized teaching credentials.
Vist our web site for additional free resources and training schedules.
|
| |
|
|