J2EE Messaging
899
// Create a topic publisher
topicSession =
topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
stockQuotesTopic = (Topic)ctx.lookup("StockQuotesTopic");
stockQuotesPublisher = topicSession.createPublisher(stockQuotesTopic);
}
public void onMessage(Message message)
{
try
{
// Extract the purchase order from the message
ObjectMessage objectMessage = (ObjectMessage)message;
PurchaseOrder order = (PurchaseOrder) objectMessage.getObject();
// Display the purchase request
System.out.println();
System.out.println("Received an order for " + order.stockQuantity() + " " +
order.stockSymbol());
}
catch(JMSException e)
{
System.out.println("Caught JMSException of: " + e.toString() );
}
}
Notice that in the publishStockQuote method, the StockGuy sets the message's JMSReplyTo header
before it sends the message. It is set to the PurchaseOrdersQueue, to indicate that if a client that receives
the stock quote wishes to purchase some of the stock it must send the purchase order to that queue:
private void publishStockQuote(String stockSymbol, int stockPrice) throws
JMSException
{
// Create the message
Integer stockPriceObj = new Integer(stockPrice);
ObjectMessage stockQuote = topicSession.createObjectMessage(stockPriceObj);
// Set the (stock) symbol property
stockQuote.setStringProperty("symbol",stockSymbol);
// Set the JMSReplyTo property, so the quote receiver will know where to send
purchase orders
stockQuote.setJMSReplyTo(purchaseOrdersQueue);
// Publish the message
stockQuotesPublisher.publish(stockQuote);
}
The StockGuy is both a receiver on the PurchaseOrdersQueue and a publisher on the
StockQuotesTopic. In the start() method, the loops allow the user to enter stock quotes, which
consist of a stock symbol and a stock price. If the user doesn't type q or Q, the StockGuy calls its
publishStockQuote() method to publish the user-inputted stock quote to the StockQuotesTopic: