Queue implements the point-to-point model. In the following example, two consumers are started to listen to a queue and then send multiple messages to the queue cyclically. We still use activemq.
Import javax. JMS. connection;
Import javax. JMS. deliverymode;
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 QueueTest {
Public static void main (String [] args) throws Exception {
ActiveMQConnectionFactory factory = new
Activemqconnectionfactory ("VM: // localhost ");
Connection connection = factory. createconnection ();
Connection. Start ();
// Create a queue
Queue queue = new activemqqueue ("testqueue ");
// Create a session
Session session = connection. createSession (false,
Session. AUTO_ACKNOWLEDGE );
// Register consumer 1
MessageConsumer comsumer1 = session. createConsumer (queue );
Comsumer1.setMessageListener (new MessageListener (){
Public void onMessage (Message m ){
Try {
System. Out. println ("consumer1 get" +
(Textmessage) M). gettext ());
} Catch (jmsexception e ){
E. printstacktrace ();
}
}
});
// Register consumer 2
MessageConsumer comsumer2 = session. createConsumer (queue );
Comsumer2.setMessageListener (new MessageListener (){
Public void onmessage (message m ){
Try {
System. Out. println ("consumer2 get" +
(Textmessage) M). gettext ());
} Catch (jmsexception e ){
E. printstacktrace ();
}
}
});
// Create a producer and send multiple messages.
MessageProducer producer = session. createProducer (queue );
For (int I = 0; I <10; I ++ ){
Producer. send (session. createTextMessage ("Message:" +
I ));
}
}
}
Run this example to get the following output:
Consumer1 get Message: 0
Consumer2 get Message: 1
Consumer1 get Message: 2
Consumer2 get Message: 3
Consumer1 get Message: 4
Consumer2 get Message: 5
Consumer1 get Message: 6
Consumer2 get Message: 7
Consumer1 get Message: 8
Consumer2 get Message: 9
It can be seen that each message is consumed once, but if multiple consumers listen to a Queue at the same time, it cannot be determined which consumer will consume the message.