background image

A Local Transaction Example

<< Difference of Messaging and Synchronized Processing | The Vendor Message Listener >>
<< Difference of Messaging and Synchronized Processing | The Vendor Message Listener >>

A Local Transaction Example

A Local Transaction Example
The TransactedExample.java program demonstrates the use of transactions in a JMS client
application. The program is in the following directory:
tut-install/javaeetutorial5/examples/jms/advanced/transactedexample/src/java/
This example shows how to use a queue and a topic in a single transaction as well as how to pass
a session to a message listener's constructor function. The program represents a highly
simplified e-commerce application in which the following things happen.
1. A retailer sends a MapMessage to the vendor order queue, ordering a quantity of computers,
and waits for the vendor's reply:
producer = session.createProducer(vendorOrderQueue);
outMessage = session.createMapMessage();
outMessage.setString(
"Item", "Computer(s)");
outMessage.setInt(
"Quantity", quantity);
outMessage.setJMSReplyTo(retailerConfirmQueue);
producer.send(outMessage);
System.out.println(
"Retailer: ordered " + quantity + " computer(s)");
orderConfirmReceiver = session.createConsumer(retailerConfirmQueue);
connection.start();
2. The vendor receives the retailer's order message and sends an order message to the supplier
order topic in one transaction. This JMS transaction uses a single session, so you can
combine a receive from a queue with a send to a topic. Here is the code that uses the same
session to create a consumer for a queue and a producer for a topic:
vendorOrderReceiver = session.createConsumer(vendorOrderQueue);
supplierOrderProducer = session.createProducer(supplierOrderTopic);
The following code receives the incoming message, sends an outgoing message, and
commits the session. The message processing has been removed to keep the sequence
simple:
inMessage = vendorOrderReceiver.receive();
// Process the incoming message and format the outgoing
// message
...
supplierOrderProducer.send(orderMessage);
...
session.commit();
3. Each supplier receives the order from the order topic, checks its inventory, and then sends
the items ordered to the queue named in the order message's JMSReplyTo field. If it does not
have enough in stock, the supplier sends what it has. The synchronous receive from the
topic and the send to the queue take place in one JMS transaction.
Creating Robust JMS Applications
Chapter 31 · The Java Message Service API
949