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.
/*** @ Author administrator * @ Description: first, create two queue. 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 accept the reply message */package COM. WL. JMS; 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 {/*** @ Param ARGs * @ throws jmsexception */public static void main (string [] ARGs) throws jmsexception {// todo auto-generated method stubactivemqconnectionfactory factory = new activemqconnectionfactory ("VM: // localhost"); connection = factory. createconnection (); connection. start (); // The message is sent to this queuequeue queue = new activemqqueue ("testqueue"); // The message is returned to this queuequeue replyqueue = new activemqqueue ("replayqueue "); final Session session = connection. createsession (false, session. auto_acknowledge); // creates a message and sets its jmsreplayto replayqueuemessage message = session. createtextmessage ("Andy"); message. setjmsreplyto (replyqueue); // create a producer to send the message messageproducer producer = session. createproducer (Queue); producer. send (Message); // Message Receiver messageconsumer consumer = session. createconsumer (Queue); consumer. 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 e) {// todo auto-generated catch blocke. printstacktrace () ;}}); // The message messageconsumer consumer2 = session used by the recipient to receive the response. createconsumer (replyqueue); consumer2.setmessagelistener (New messagelistener () {public void onmessage (message m) {try {system. out. println (textmessage) M ). gettext ();} catch (jmsexception e) {// todo auto-generated catch blocke. printstacktrace ();}}});}}
First, the message producer sends a message with the content of "Andy". Then, after receiving the message, the consumer replies a message with the content of "Hello Andy" based on the message's jmsreplyto '. 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: