read jms message from queue using selector

1.6k views Asked by At

I have a client in java which send a jms message in a queue ("queue-request"). The message contains a int property ("id") containing the unique client id number. The message is being processed and than lands in another queue ("queue-respond"). How can let the client wait till the message with his id is in the queue and then read it out. I have tried to use a listener and implement the onMessage but how can I then stop listening when the message is received?

2

There are 2 answers

3
Mani On

JMS synchronous can be acchived using JMSReplyTo . Create Temp Queue while sending orginal Message with the same session. Start Listen the Temp Queue and set the Original Message JMSReplyTo the TmpQueue.

Use TempQueue Receiver.receive() to make the thread wait ( synchronous)

Complete sample code can be found in

http://jmsexample.zcage.com/

0
tonga On

In JMS you need to specify the listener for the queue so that if the message is sent, then the particular listener is selected to receive the message. In Spring you can specify the listener in the bean configuration file, as an example:

<bean id="myListener" class="mypackage.MyMessageListener" />

<bean id="queueBean" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg value="Queue-Request"/>
</bean>

<bean id="myListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactoryBean" />
    <property name="destination" ref="queueBean" />
    <property name="messageListener" ref="myListener" />
</bean>

Then you can write the class MyMessageListener to implement the MessageListener interface:

public class MyMessageListener implements MessageListener {
    public void onMessage(Message message) {
        //handle message here ...
    }   
}

This will ensure that MyMessageListener will get the message sent from the queue. Note that Queue is p2p, so if the message is received by MyMessageListener, it will not be received by other listeners which don't subscribe to this queue.