Monday, June 15, 2009

JMS easy example, Get start with JMS, JMS tutorial, JMS easy code


JMS : Java Messaging Service

I was searching an easy and running example on JMS, but could not. I saw in many tutorial they explained in very hard manner to how to setup the administrative object to run the JSM example. But in real it is very easy.
Here I am using IBM Rational Software Architect (RSA) as Java IDE and WebSphere Application Server V6.1 that comes with RSA. [ Image Source ]
NOTE : If you want to execute this tutorial on RAD [IBM Rational Architect Developer] IDE then plesae click below link.

Just follows these step and your example will run:

1. start the server and go to admin console
2. Service Integration -> Buses -> New -> Give Bus Name: BinodBus ->
Next -> Finish
3. click on BinodBus -> In Topology Section, click on Bus Member -> Add -> next -> Chosse File Store -> next -> next -> Finish -> Save
4. Agin click on BinodBus -> In Destination Resource, click on Destination -> check Queue Type present or not. If not present then click on Next -> Choose Queue -> Next ->
put Identifier QueueDestination -> Next -> Finish -> Save
5. Open Resources Tree from left panel

6. click on JMS -> Connection Factories -> New -> Choose Default messaging provider -> OK -> Name -> BinodConnectionProvider ->
JNDI Name -> jms/BinodConnectionProvider -> Bus Name -> BinodBus ->
click on OK -> Save

7. From left side Resources -> JMS -> Queue -> New -> choose Default messaging provider -> OK ->
Name -> BinodQueue -> JNDI -> jms/BinodQueue -> Bus Name ->
BinodBus -> QueueName -> QueueDestination -> OK -> Save

[All the bold latter is Admin object name]

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. I am able to write this article after a lot struggle.
Source of example.

44 comments:

  1. Woohoo awesome job. First time I got an easy example on JMS. Any one can start JMS with this easy example. Thanks a lot.

    Sachin, HYD

    ReplyDelete
  2. Thanks for your appreciation and keeping hope for your suggestion to improve this blog.

    Thanks,

    Binod Suman
    http://binodsuman.blogspot.com

    ReplyDelete
  3. Good tutorial. I have also got one more good link http://sacrosanctblood.blogspot.com/2008/11/jms-tutorial-topic-subscriber-client.html

    Thanks,
    Mike

    ReplyDelete
  4. Good tutorial. I have also got one more good link http://sacrosanctblood.blogspot.com/2008/11/jms-tutorial-topic-subscriber-client.html

    Thanks,
    Mike

    ReplyDelete
  5. Thanks for taking the time to help, I really apprciate it.

    http://dealzfirst.com/Just+My+Size+JMS-3.htm

    ReplyDelete
  6. That is Good Exmple.just one more thing I want Jms with topic example could you please help me

    This is my mail-idkrishnamurthy@hcl.in

    please help me

    ReplyDelete
  7. Thanks Binod.

    Nicely simplified example.

    best regards,

    Shaun D.

    ReplyDelete
  8. Hi Suman

    Thanks for such a good application and is very easy to understand for the beginners..

    Rajesh(SE)

    ReplyDelete
  9. It really helped me a lot

    ReplyDelete
  10. Hi Binod,

    Its very nice job for begineers.


    It will be helpfule for me,If you help me figure out JSF and Spring.

    Thanks & Regards,
    Jain

    ReplyDelete
  11. The most concise explanation to get started with JMS. Well done Binod Keep doing good job

    ReplyDelete
  12. Superb tutorial.

    ReplyDelete
  13. I am a bigginer to JMS. This tutorial helped me a lot . Can you pls send some more asynchronous examples

    ReplyDelete
  14. I really hope these System.exit(1) calls are not your favourite way of dealing with exceptions.

    ReplyDelete
  15. Very Nice example. It came the first result on google for my search. Thanks very much:)

    ReplyDelete
  16. Really good one..thanks a lot, I went through so many articles to understand this simple thing!!

    ReplyDelete
  17. Hi,

    Many thanks for your great tutorial.
    One question; how can we connect to a remote websphere?

    What are the code changes for this purpose?

    ReplyDelete
  18. Thanks, Mr. Binod Suman, I have tested it successfully on glassfish 3.0.1. Keep up the good work!

    ReplyDelete
  19. Thaks.
    But i have some problem when is use security for bus.

    How for do it.

    thank for reply.

    ReplyDelete
  20. Hai its nice example! could u tell us how to deploy jms on weblogic8.1......

    ReplyDelete
  21. Hi Binod,

    Really nice work this.
    I migrated your example to Weblogic 10g in a Java Main class. Really appreciate your work. It made me understand the basic working of JMS.
    Siddharth Singh

    ReplyDelete
  22. Hi binod
    when i am trying this get error like
    [7/21/11 15:13:38:890 IST] 00000052 SibMessage E [:] CWSIQ0017E: The sender channel MQ_SENDER_CHANNEL for MQLink TESTSIB_LINK has failed to establish a connection with the remote host localhost/127.0.0.1 because the remote listener for port 2020 is not available.

    how can i rectify

    ReplyDelete
  23. Its once of the fantastic blog i ever seen. Its very simple and very use full. Its really good for evry level of developer.

    ReplyDelete
  24. Wonderful, too good.I simply loved the example

    ReplyDelete
  25. This is a good and a pragmatic article on JMS. It is very helpful in understanding the workings of JMS.

    Thank you

    ReplyDelete
  26. Hi Binod,

    Really, this is good example.

    I appreciate you.

    Thanks
    SinghRaj
    Princesscruises

    ReplyDelete
  27. Thank you for this example!

    ReplyDelete
  28. Thanks! After long time at last have found a working example without EJB. Good one really.
    Thanks a lot!

    ReplyDelete
  29. Good work Binod.

    Its really good example..

    BestRegards,
    Suresh Mopada

    ReplyDelete
  30. Thanks Binod, This has been one of the best article for the JMS Beginner.

    Tribhuwan

    ReplyDelete
  31. explanation is good ... thank you

    ReplyDelete
  32. rielly rielly good tutorial

    ReplyDelete
  33. Really Good tutorial. I was able to setup the example exactly as described. Thanks a lot.

    I made a couple of tweaks to the example in my version so it was a little easier to see.

    At the moment the output goes to the log file and not the web page, so I added a println() method which writes to both. That way the user gets something on their web browser and also in the log file.

    Changed code from :

    check();
    }

    public void check() {

    Changed to:

    check(response.getWriter());
    }

    public void println(PrintWriter out,String message){
    System.out.println(message);
    out.println("<p>");
    out.println(message);
    out.println("</p>");
    }

    public void check(PrintWriter out) {

    Then change each :

    System.out.println("some text");

    changed to :

    println(out,"some text at "+System.currentTimeMillis());

    ReplyDelete
  34. Very simple and easy to understand

    ReplyDelete
  35. Very Nice ....

    Exactly what I was looking .... Thank you very much for putting this together.

    ReplyDelete
  36. thank vry much Binod.please send me documentation on jms to khaja.sendme@gmail.com

    ReplyDelete
  37. Hi Binod,

    Thanks for the above examples

    It would be great if you can help me out with a java program which monitors a queue continuously. Thanks in advance.

    Ajith

    ReplyDelete
  38. Nice tutorial. Easy to start JMS

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)