background image

Creates a Connection and a Session

<< Synchronous Receive Example | Consume System Resources >>
<< Synchronous Receive Example | Consume System Resources >>

Creates a Connection and a Session

e.printStackTrace();
System.exit(1);
}
4. Creates a Connection and a Session:
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
5. Creates a MessageProducer and a TextMessage:
MessageProducer producer = session.createProducer(dest);
TextMessage message = session.createTextMessage();
6. Sends one or more messages to the destination:
for (int i = 0; i < NUM_MSGS; i++) {
message.setText(
"This is message " + (i + 1));
System.out.println(
"Sending message: " + message.getText());
producer.send(message);
}
7. Sends an empty control message to indicate the end of the message stream:
producer.send(session.createMessage());
Sending an empty message of no specified type is a convenient way to indicate to the
consumer that the final message has arrived.
8. Closes the connection in a finally block, automatically closing the session and
MessageProducer
:
} finally {
if (connection != null) {
try { connection.close(); }
catch (JMSException e) { }
}
}
The receiving program, synchconsumer/src/java/SynchConsumer.java, performs the
following steps:
1. Injects resources for a connection factory, queue, and topic.
2. Assigns either the queue or topic to a destination object, based on the specified destination
type.
3. Creates a Connection and a Session.
4. Creates a MessageConsumer:
consumer = session.createConsumer(dest);
Writing Simple JMS Client Applications
Chapter 31 · The Java Message Service API
913