I would like to use a standalone java program to poll and retrieve messages from JMS queue instead of having an MDB. Is it possible?
If it is, would it be possible to share any examples / links? Thanks.
Regards,V
I agree with the other response that Spring JMS is simple (providing you know a bit of Spring, and have the framework) but it's quite straightforward from plain old Java too. Just write some code within main to setup a ConnectionFactory, Connection, and Session, e.g. see
http://download.oracle.com/javaee/1.4/tutorial/doc/JMS4.html
you can either look up a ConnectionFactory from JNDI or instantiate a provider-specific one yourself; e.g. for WebSphere MQ you would write something like:
MQConnectionFactory cf = new MQConnectionFactory();
cf.setHostName(HOSTNAME);
cf.setPort(PORT);
cf.setChannel(CHANNEL);
cf.setTransportType(WMQConstants.WMQ_CM_CLIENT);
(other providers are available, I just can't write the code off the top of my head :) then standard JMS
Connection c = cf.createConnection();
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue q = s.createQueue("myQueue");
MessageConsumer c = s.createConsumer(q);
at this point you have two options. You could create a javax.jms.MessageListener implementation and set it on the MessageConsumer, or if you want more direct control you can either kick off a Thread that uses the MessageConsumer to do either a get-with-wait (receive(int timeout)) or a get with no wait (receiveNoWait()) and then a sleep until the next receive. Don't use receive() though, it's never a good idea with JMS. If you want more than one polling thread then you should check the concurrency restrictions on JMS Session/Consumer objects.
Don't forget to call Connection.start() once the setup is done if you want anything to happen
Advantages are you only need your JMS provider .jars on the classpath, no framework etc. Disadvantages are that it's more complex than Spring, which provides quite an elegant solution to this - note how much setup code there is here, compared to Spring which abstracts it all out. Really depends on your preferences, other requirements etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With