23.07.2013 Views

O'Reilly - Java Message Service

O'Reilly - Java Message Service

O'Reilly - Java Message Service

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}<br />

"interim messages");<br />

processCompensatingTransaction( );<br />

}<br />

} else {<br />

System.out.println ("\nBad Deal. Not buying");<br />

}<br />

} catch (javax.jms.JMSException jmse){<br />

jmse.printStackTrace( );<br />

}<br />

<strong>Java</strong> <strong>Message</strong> <strong>Service</strong><br />

The first message (surfboards) is processed by the call to a very simple helper method,<br />

processInterim<strong>Message</strong>s( ), that exists only to simulate the processing of the initial<br />

message:<br />

private void autoBuy (javax.jms.<strong>Message</strong> message){<br />

int count = 1000;<br />

try {<br />

...<br />

if ( saveDesc == null){<br />

if (message.getJMSRedelivered( ))<br />

processCompensatingTransaction( );<br />

processInterim<strong>Message</strong>s( itemDesc );<br />

return;<br />

}<br />

...<br />

}<br />

}<br />

private String saveDesc = null;<br />

private void processInterim<strong>Message</strong>s(String itemDesc)<br />

{<br />

saveDesc = itemDesc;<br />

}<br />

processInterim<strong>Message</strong>s( ) saves the item description, which will be used later when the<br />

second message arrives. In a real application, you can envision that the call to<br />

processInterim<strong>Message</strong>s( ) would perform some real work, executing some business logic<br />

and placing data in a database table in preparation for the next message. We will get to the<br />

redelivered case shortly.<br />

The next important piece to examine is the placement of the call to the acknowledge( )<br />

method. It is called once, after both messages have been received:<br />

private void autoBuy (javax.jms.<strong>Message</strong> message){<br />

int count = 1000;<br />

try {<br />

...<br />

try {<br />

System.out.println("\nAcknowledging messages");<br />

message.acknowledge( );<br />

System.out.println("\n<strong>Message</strong> acknowledged");<br />

saveDesc = null;<br />

} catch (javax.jms.JMSException jmse){<br />

...<br />

}<br />

Calling the acknowledge( ) method on a message acknowledges the current message and<br />

all previously unacknowledged messages. Because the autoBuy( ) logic does not respond<br />

with a buy order until it sees the second message, it also does not explicitly acknowledge<br />

the receipt of the message until it knows it can process both at the same time. This logic<br />

93

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!