Receiving Messages Synchronously

Receiving messages synchronously works much in the same way that sending a message works in that they both use the JmsTemplate class. When receiving messages synchronously the application receiver class blocks until a message is received from the queue or topic. Like the send methods on the JmsTemplate, there are two forms of receive methods; receive and receiveAndConvert. The receive method returns a JMS Message object, whereas the receiveAndConvert method returns a Java Object corresponding to the type of JMS Message object received. Like the send method, you can use a default destination or specify the JNDI name or JMS destination directly in the receive method itself.

The receiver timeout value allows you to control the amount of time the application receiver should wait before receiving a message. The default value is 0, indicating that the receiver should block and wait forever until a message is received. The receiver timeout value can be specified through the receiveTimeout property on the JmsTemplate bean. This property takes a long value containing of the receive timeout in milliseconds. For example, receivers using the JmsTemplate defined here will stop waiting for messages after 30 seconds:

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="queueConnectionFactory"/> <property name="destinationResolver" ref="destinationResolver"/> <property name="defaultDestinationName" value="queue1"/> ...

Get Java Message Service, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.