6.4.3. Publishing Messages to a Queue
This section describes Producer.java, which sends messages to the direct exchange. The producer class is derived from BaseExample, which gives it access to the JNDI environment described in the previous section.
Before we can publish messages, we must have an open connection, a session, and a destination queue. First we get a connection factory using JNDI:
// Load JNDI properties
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("direct.properties"));
//Create the initial context
Context ctx = new InitialContext(properties);
// look up destination and connection factory
Destination destination = (Destination)ctx.lookup("directQueue");
ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("qpidConnectionfactory");
Create the connection and the session using this connection factory:
Connection connection = conFac.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Create a MessageProducer and a message, using the Message object to send a series of messages in a loop.
In Java JMS, we do not need to start the connection in order to send a message. We do need to start a connection in order to receive a message.
MessageProducer messageProducer = session.createProducer(destination);
TextMessage message;
// Send a series of messages in a loop
for (int i = 1; i < getNumberMessages() + 1; i++)
{
message = session.createTextMessage("Message " + i);
messageProducer.send(message, getDeliveryMode(), Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
}
After sending the messages, send a final termination message:
message = session.createTextMessage("That's all, folks!");
messageProducer.send(message, getDeliveryMode(), Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
Now we need only close the connection and the JNDI context.
connection.close(); getInitialContext().close();