Connecting to a remote JMS Queue

Vishu Guntupalli
Intelicloud
Published in
2 min readMay 23, 2015

I have been working on JMS Queues for a while now and I wanted to take sometime to blog about how to connect to a remote JMS queues and write messages to it. I am using Spring to configure the connection settings and will use simple java class to load the spring context and write to the queue.

You need to have the following beans in your Jms context file.

Snip20150522_1

The first bean is the JndiTemplate which is used to help in working with remote JNDI objects. It consists of fields like the following

  • java.naming.factory.initial : Usually the initial context factory, the implementation differs from server to server.
  • java.naming.provider.url : The URL of the server where the JMS objects are located.
  • java.naming.security.principal: The username
  • java.naming.security.password: Password

The second bean is the JndiObjectFactoryBean which consists of several flags which can be configured according to the users need. A list of all configurable fields can be looked up here.

I would like to point to the fact that we are injecting the jndiTemplate(The first bean we defined) into the jndiObjectFactoryBean. We are also providing the jndiName which is usually the JMSConnectionFactory name configured on the server.

After we are done configuring the context file we can connect to the Queue and send messages to it through the QueueConnectionFactory

QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(username,password);
queueConnection.start();
// Create request Queue
QueueSession queueSession = queueConnection.createQueueSession( false, Session.AUTO_ACKNOWLEDGE );
Queue queue = queueSession.createQueue( queueName );
String expectedRequestXml = FileUtils.resourceContentsAsString( “xml/sample.xml” );
Message message = queueSession.createTextMessage( expectedRequestXml );
QueueSender queueSender=queueSession.createSender(queue);
queueSender.send( message );
queueSender.close();
queueSession.commit();
queueSession.close();
queueConnection.close();

The following are the objects you would need to create to connect and a message to a queue.

  • QueueConnectionFactory → QueueConnection (with username and password as arguments)
  • QueueConnection → QueueSession
  • QueueSession → Queue ( With queue name as the argument)
  • QueueSession → QueueSender ( With the Queue as argument)
  • QueueSession → Message (With the message you want to send as argument)

Start the queueConnection before all this and queueSender.send(message) then close the queueSender, queueSession and queueConnection.

You should be able to connect and send message to a queue using this, please comment about your thoughts or any questions you might have.

--

--

Vishu Guntupalli
Intelicloud

Software engineer/architect, Entrepreneur, AWS, Python, Data, Cloud