In the following example, two queue are created, and the sender sends a message to one queue. After receiving the message, the receiver replies a message to the other queue, then create a consumer to receive the reply message.
Import javax. JMS. connection;
Import javax. JMS. jmsexception;
Import javax. JMS. message;
Import javax. JMS. messageconsumer;
Import javax. JMS. messagelistener;
Import javax. JMS. messageproducer;
Import javax. JMS. Queue;
Import javax. JMS. Session;
Import javax. jms. TextMessage;
Import org. apache. activemq. ActiveMQConnectionFactory;
Import org. apache. activemq. command. ActiveMQQueue;
Public class MessageSendReceiveAndReply {
Public static void main (String [] args) throws Exception {
ActiveMQConnectionFactory factory = new
ActiveMQConnectionFactory ("vm: // localhost ");
Connection connection = factory. createConnection ();
Connection. start ();
// Send the message to this Queue
Queue queue = new ActiveMQQueue ("testQueue ");
// The message is returned to this Queue
Queue replyQueue = new ActiveMQQueue ("replyQueue ");
Final Session session = connection. createsession (false,
Session. auto_acknowledge );
// Create a message and set its jmsreplyto to replyqueue.
Message message = session. createtextmessage ("Andy ");
Message. setjmsreplyto (replyqueue );
Messageproducer producer = session. createproducer (Queue );
Producer. send (message );
// Message recipient
MessageConsumer comsumer = session. createConsumer (queue );
Comsumer. setMessageListener (new MessageListener (){
Public void onMessage (Message m ){
Try {
// Create a new MessageProducer to send a reply message.
MessageProducer producer =
Session. createProducer (m. getJMSReplyTo ());
Producer. send (session. createTextMessage ("Hello"
+ (TextMessage) m). getText ()));
} Catch (JMSException e1 ){
E1.printStackTrace ();
}
}
});
// This receiver is used to receive the reply message
MessageConsumer comsumer2 =
Session. createConsumer (replyQueue );
Comsumer2.setMessageListener (new MessageListener (){
Public void onMessage (Message m ){
Try {
System. out. println (TextMessage) m). getText ());
} Catch (JMSException e ){
E. printStackTrace ();
}
}
});
}
}
First, the message producer sends a message whose content is "Andy ",
Then, after receiving the message, the consumer replies a message based on the jmsreplyto of the message, with the content "Hello Andy '.
Finally, create a consumer in the reply queue to receive the reply message, and output the reply content.
Run the above program to get the following output:
Hello Andy