Steps to send and receive messages using JMS
However, before we start using JMS APIs, let's take a look at the generic steps involved in using them. The following steps show how to send a message to a queue and receive it. Although the steps focus on queues, the steps for topics are similar, but with appropriate topic-related classes:
- Look up
ConnectionFactory
using JNDI:
InitialContext ctx = new InitialContext(); QueueConnectionFactory connectionFactory = (QueueConnectionFactory)initCtx.lookup("jndi_name_of_connection_factory");
- Create a JMS connection and start it:
QueueConnection con = connectionFactory.createQueueConnection(); con.start();
- Create a JMS session:
QueueSession session = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
- Look up JMS
Queue
/Topic
:
Queue queue = (Queue)initCtx.lookup("jndi_queue_name");
- For sending messages, perform the following steps:
- Create a sender:
QueueSender sender = session.createSender(queue);
- Create the message. It can be of any of the following...