Tuesday, June 16, 2009

JMS easy example in RAD, Get started with JMS on RAD

This tutorial is based on RAD (Rational Architect Development) that uses the WebShpere Application Server V6.0.

1. start the server and go to admin console
2. Service Integration -> Buses -> New -> Give Name: BinodBus -> Apply -> save -> save
3. click on BinodBus -> In Additional Properties Section, click on Bus Member -> Next -> Finsh -> Save -> save
4. Again click on BinodBus -> In Additional Properties Section, click on Destination -> check Queue Type present or not. If
not present then click on New -> Choose Queue -> Next -> put Identifier QueueDestination -> Next -> Finish -> Save -> Save

5. Open Resources Tree from left panel
6. click on JMS Providers -> Default Messaging -> JMS Connection Factory -> New -> Name -> BinodConnectionProvider -> JNDI
Name -> jms/BinodConnectionProvider -> Bus Name -> BinodBus -> click on Apply -> Save -> Save

7. click on JMS Providers -> Default Messaging -> Go to Right side Destination -> JMS Queue -> New -> Name -> BinodQueue ->
JNDI -> jms/BinodQueue -> Bus Name -> BinodBus -> QueueName -> QueueDestination -> OK -> Save -> Save

8. Restart the server.
9. Create one Dynamic Web Project (JMSSECOND)and Write two servlet to check the simple example

10. Write first servlet (ProducerServlet.java)

import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProducerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("******** THIS IS MESSAGE PRODUCER SERVLET **********");
check();
}

public void check(){
System.out.println("********* Producer check **********");
String destName = "jms/BinodQueue";
final int NUM_MSGS = 5;
Context jndiContext = null;

try { jndiContext = new InitialContext(); }
catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
}

ConnectionFactory connectionFactory = null;
Destination dest = null;

try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
dest = (Destination) jndiContext.lookup(destName); }
catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); e.printStackTrace(); System.exit(1);
}

Connection connection = null;
MessageProducer producer = null;
try {
connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(dest);
TextMessage message = session.createTextMessage();

for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message from JMSSECOND DEMO " + (i + 1));
System.out.println("Sending message: " + message.getText());
producer.send(message);
}

producer.send(session.createMessage());
} catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
finally { if (connection != null) { try { connection.close(); }
catch (JMSException e) { }
}
}
}
}

11. Write second servlet (ConsumerServlet.java)

import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConsumerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("********** MESSAGE CONSUMER SERVLET 2 ************");
check();
}

public void check(){
System.out.println("********* Consumer check **********");
String destName = "jms/BinodQueue";
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination dest = null;
MessageConsumer consumer = null;
TextMessage message = null;
System.out.println("Destination name is " + destName);

try {
jndiContext = new InitialContext();
}catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
}

try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
dest = (Destination) jndiContext.lookup(destName);
} catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); System.exit(1);
}

try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(dest);
connection.start();
while (true) {
Message m = consumer.receive(1);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " + message.getText()); }
else { break; }
}
}
} catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
finally { if (connection != null) { try { connection.close(); }
catch (JMSException e) { }
}
}
}
}

First run Producer Servlet:
http://localhost:9080/JMSSECOND/ProducerServlet
Output:

Sending message: This is message from JMSSECOND DEMO 1
Sending message: This is message from JMSSECOND DEMO 2
Sending message: This is message from JMSSECOND DEMO 3
Sending message: This is message from JMSSECOND DEMO 4
Sending message: This is message from JMSSECOND DEMO 5

Then run Consumer Servlet:
http://localhost:9080/JMSSECOND/ConsumerServlet
Output:


Reading message: This is message from JMSSECOND DEMO 1
Reading message: This is message from JMSSECOND DEMO 2
Reading message: This is message from JMSSECOND DEMO 3
Reading message: This is message from JMSSECOND DEMO 4
Reading message: This is message from JMSSECOND DEMO 5

Please put your comments to give better information in next blog. :)
Source of example.

7 comments:

  1. Good tutorial on JMS. I just copied your code and set all the administrative object in admin console and got working. Many thanks.
    Could you please give some Asynchronous messging example. Again Thanks.

    ReplyDelete
  2. Thanks for your appreciation. I will try to give some example on Ashynchronous JMS easy example in coming weekend. Keep watching this blog and give suggestion to improve this blog.

    Thanks,

    Binod Suman
    http://binodsuman.blogspot.com

    ReplyDelete
  3. I tried these settings on RAD 7.0.0, but it did not work. While lookup operation it is throwing an exception "javax.naming.NoInitialContextException". If you have any idea please tell me.

    Regards
    R Kumar

    ReplyDelete
  4. This is very useful article to learn JMS

    -Sudhakar

    ReplyDelete
  5. Hi,
    This blog seems to be old one, but very effective. Followed step by step and worked perfectly. But one thing I am puzzled. In your producerServlet you are pushing 5 messages(NUM_MSGS = 5) using for loop for (int i = 0; i < NUM_MSGS; i++).
    Then how the message depth is showing 6 when I looked into my Queue using Admin Console. The sixth message is empty when I looked into the body. Would be good if can explain why the sixth message getting created...

    ReplyDelete
  6. Gotcha below needs to be commented:
    //producer.send(session.createMessage());

    ReplyDelete
  7. Do I need to update web.xml to run the above servlets? I got page can't be displayed error after running the servlet. Please let me know

    ReplyDelete

Please put your feedback or your any question related to this blog. Thanks.