This is an example for Simple message driven bean with GlassFish server and NetBeans. We can use message driven bean to asynchronously process messages. Although you can use session bean to synchronously process messages but it is bit expensive to block message processing with synchronization since it is eating server resources. Following are the summery of steps for this example.
· Creating web application with NetBeans
· Creative required JMS connection factory and queue in the GlassFish server.
· Creating Servlet (MessageProducerServlet) to put messages into the JMS queue.
· Creating message driven bean (SimpleMessageBean) to process messages from JMS queue
The architecture of the example
With the MessageProducerServlet we are producing messages and put them into the JMS queue. The SimpleMessageBean is listing to the JMS queue and ones the message arrived the onMassage() on SimpleMessageBean is invoked.
Creating web application with NetBeans
Open NetBeans IDE and File à New Project à Java Web à Web Application
Creative required JMS connection factory and queue in the GlassFish server.
Open the browser for url http://localhost:4848/ and you will directed to the GlassFish administrator UI. First we need to create JMS ConnectionFactory in the server. Go to resources à JMS resources à Connection Factories à New, give name as jms/MyConnectionFactory and select resource type as ‘javax.jms.ConnectionFactory’.
Then we need to create JMS queue and go to resources à JMS resources à Destination Resources à New, give name as jms/MyQueue and select resource type as ‘javax.jms.Queue’ and Destination name as ‘PhysicalQueue’.
We need to create the ConnectionFactory and queue on the GlassFish server. Since server to server default ConnectionFactory and queue is changing I am not using the defaults.
Creating Servlet (MessageProducerServlet) to put messages into the JMS queue.
I choose servlet to put messages into the JMS queue because it is very easy when reffering ConnectionFactory and Queue. We are referring ConnectionFactory and Queue with resource annotation (dependency injection) so we need to run this on the GlassFish server. If we are using outside GlassFish server we should do JNDI lookup.
To create Servlet for the project right click the project and create Servlet and add following code into it. When creating the servlet remember to add servlet information to the web.xml.
package org.sun.exam.message.producer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MessageProducerServlet extends HttpServlet {
@Resource(mappedName = "jms/MyConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/MyQueue")
private Queue queue;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
sendMessages();
} catch (Exception ex) {
Logger.getLogger(MessageProducerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
private int NUM_MSGS = 3;
public void sendMessages() throws Exception {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(queue);
TextMessage message = session.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " + message.getText());
messageProducer.send(message);
}
}
Creating message driven bean (SimpleMessageBean) to process messages from JMS queue
Our message driven bean does not directly communicate with Servlet, it is using JMS queue to listen to messages. To create message driven bean for the project right click the project and create new message driven bean and add following code into it.
package org.sun.exam.message.bean;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
@MessageDriven(mappedName = "jms/MyQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class SimpleMessageBean implements MessageListener {
@Resource
private MessageDrivenContext mdc;
public SimpleMessageBean() {
}
public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
if (inMessage instanceof TextMessage) {
msg = (TextMessage) inMessage;
System.out.println("MESSAGE BEAN: Message received: " + msg.getText());
//logger.info("MESSAGE BEAN: Message received: " + msg.getText());
} else {
System.out.println("Message of wrong type: " + inMessage.getClass().getName());
//logger.warning("Message of wrong type: " + inMessage.getClass().getName());
}
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
}
In this example with the message driven bean we have used asynchronous message consumption. When is comes to JMS there are two types of consumers,
Synchronously: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.
Asynchronously: A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message
Note:
This example based on Java EE6 tutorial and in the reference you can find the link.
Reference:
http://download-llnw.oracle.com/javaee/6/tutorial/doc/bnbpk.html
2 comments:
Thanks for that... :-)
can you tell me why my glassfish cannot function well? i did as your posted. but i still cannot add ant new connection factory or destination through the localhost.. hope you can help me.. tq
Post a Comment