6.5.5. Publishing Messages to a Fanout Exchange
This section describes Producer.java, which sends messages to a fanout 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("fanout.properties"));
// Create the initial context
Context ctx = new InitialContext(properties);
Destination destination = (Destination)ctx.lookup("fanoutQueue");
// Declare the connection
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 < numMessages + 1; i++)
{
message = session.createTextMessage("Message " + i);
messageProducer.send(message, deliveryMode, 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, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
Now we need only close the connection and the JNDI context.
connection.close(); ctx.close();