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. 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
  6. Thanks Binod.

    Nicely simplified example.

    best regards,

    Shaun D.

    ReplyDelete
  7. Hi Suman

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

    Rajesh(SE)

    ReplyDelete
  8. It really helped me a lot

    ReplyDelete
  9. 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
  10. The most concise explanation to get started with JMS. Well done Binod Keep doing good job

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

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

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

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

    ReplyDelete
  15. 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
  16. Thanks, Mr. Binod Suman, I have tested it successfully on glassfish 3.0.1. Keep up the good work!

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

    How for do it.

    thank for reply.

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

    ReplyDelete
  19. 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
  20. 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
  21. 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
  22. Wonderful, too good.I simply loved the example

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

    Thank you

    ReplyDelete
  24. Hi Binod,

    Really, this is good example.

    I appreciate you.

    Thanks
    SinghRaj
    Princesscruises

    ReplyDelete
  25. Thank you for this example!

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

    ReplyDelete
  27. Good work Binod.

    Its really good example..

    BestRegards,
    Suresh Mopada

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

    Tribhuwan

    ReplyDelete
  29. explanation is good ... thank you

    ReplyDelete
  30. rielly rielly good tutorial

    ReplyDelete
  31. 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
  32. Very simple and easy to understand

    ReplyDelete
  33. Very Nice ....

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

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

    ReplyDelete
  35. 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
  36. Nice tutorial. Easy to start JMS

    ReplyDelete

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