From: http://blog.163.com/chengwei_1104/blog/static/53645274201382315625329/
ActiveMQ is the most popular, powerful, open source messaging bus that Apache has produced. ActiveMQ is a JMS provider implementation that fully supports the JMS1.1 and the Java EE 1.4 specification, although the JMS specification has been around for a long time, but JMS still plays a special role in the middle of today's Java EE applications.
The following explains in detail the role of common classes
ConnectionFactory Interface (Connection factory) a managed object that the user uses to create a connection to the JMS provider. The JMS client accesses the connection through a portable interface so that the code does not need to be modified when the implementation of the current layer changes. The administrator configures the connection factory in the Jndi namespace so that JMS clients can find them. Depending on the message type, the user will use the Queue connection factory, or the subject connection factory.
The Connection interface (connection) connection represents the communication link between the application and the messaging server. Once you have a connection factory, you can create a connection to the JMS provider. Depending on the connection type, the connection allows the user to create a session to send and receive queues and topics to the destination.
The Destination interface (target) target is a managed object that wraps the message target identifier, which is the location where the message is published and received, or whether it is a queue, or a subject. The JMS administrator creates these objects and then the user discovers them through Jndi. Like a connection factory, an administrator can create two types of targets, a queue of point-to-point models, and a topic for the publisher/subscriber model.
Messageconsumer Interface (message consumer) an object created by the session to receive messages sent to the destination. Consumers can synchronize (block mode), or asynchronous (non-blocking) messages that receive queues and subject types.
The MessageProducer interface (message producer) is an object created by the session that is used to send messages to the destination. Users can create a sender for a target, or they can create a generic sender that specifies a target when sending a message.
Message interfaces (messages) are objects that are transferred between consumers and producers, that is, from one application to another. A message has three main parts: the message header (must): Contains the action settings that are used to identify and find the route for the message. A set of message properties (optional): Contains additional attributes that support compatibility with other providers and users. You can create custom fields and filters (message selectors). A message body (optional): Allows the user to create five types of messages (text messages, map messages, byte messages, stream messages, and object messages). The messaging interface is flexible and provides many ways to customize the content of the message.
Session interfaces (sessions) represent a single thread context for sending and receiving messages. Because the session is single-threaded, the message is sequential, meaning that the message is received one at a time in the order in which it was sent. The advantage of a session is that it supports transactions. If the user chooses transaction support, the session context saves a set of messages until the transaction is committed. Users can cancel these messages by using a rollback operation before committing the transaction. A session allows users to create message producers to send messages and create message consumers to receive messages.
Session interfaces (sessions) represent a single thread context for sending and receiving messages. Because the session is single-threaded, the message is sequential, meaning that the message is received one at a time in the order in which it was sent. The advantage of a session is that it supports transactions. If the user chooses transaction support, the session context saves a set of messages until the transaction is committed. Users can cancel these messages by using a rollback operation before committing the transaction. A session allows users to create message producers to send messages and create message consumers to receive messages.
The JMS message pattern has
1. Peer-to-peer message mode (point-to-point Messaging)
2. Publish subscription model (Publish–subscribe mode)
Here, based on the point-to-point message pattern Analysis of the ACTIVEMQ message and the process of receiving messages, see the Model diagram:
The point-to-point message is sent primarily on message queue,sender,reciever, message Queue storage messages, Sneder (client A) sends messages, receive (client B) receives messages. The specific point is that client a sends a message queue, and client B receives messages from the queue and "sends messages accepted" to Quere, confirming that the message is received. The message sending client has no time dependency on the receiving client, and the sending client can send the message to the queue at any time without needing to know whether the receiving client is running.
PackageCom.activemq.queue;Importjava.util.Date;Importjavax.jms.Connection;Importjavax.jms.ConnectionFactory;Importjavax.jms.Destination;Importjavax.jms.JMSException;ImportJavax.jms.Message;ImportJavax.jms.MessageConsumer;ImportJavax.jms.MessageListener;ImportJavax.jms.MessageProducer;Importjavax.jms.Session;ImportJavax.jms.TextMessage;Importorg.apache.activemq.ActiveMQConnection;Importorg.apache.activemq.ActiveMQConnectionFactory; Public classActivemqtest {Private StaticString queuename = "Activemq_queue_"; Public Static voidMain (string[] args) {receiver receiver=NewReceiver (); Sender Sender=NewSender ();Try{sender.send (); receiver.receive ();}Catch(Exception e) {e.printstacktrace ();}} Static classReceiver { Public Static voidReceive ()throwsException {connectionfactory connectionfactory=Newactivemqconnectionfactory (); Connection Connection=connectionfactory.createconnection (); Connection.start (); Session Session=connection.createsession (Boolean.true, Session.auto_acknowledge); Destination Destination=Session.createqueue (queuename); Messageconsumer Consumer=Session.createconsumer (destination);//first Case inti = 0; while(I < 3) {i++; TextMessage message=(TextMessage) consumer.receive (); Session.commit ();//TODO something ....System.out. println ("Received message:" +Message.gettext ()); } session.close (); Connection.close (); //----------------The first case is over----------------------//The second way//Consumer.setmessagelistener (New MessageListener () {//Public void OnMessage (Message arg0) {//if (arg0 instanceof textmessage) {//try {//System.out.println ("arg0=" + ((textmessage) arg0). GetText ());//} catch (JMSException e) {//e.printstacktrace ();// }// }// }// }); //The third case//While (true) {//Message msg = consumer.receive (+);//textmessage message = (textmessage) msg;//if (null! = message) {//System.out.println ("received message:" + message.gettext ());//}//}} }
Static Class Sender {
Public Static voidSend() Throws Exception {
ConnectionFactoryConnectionFactory= Null;
ConnectionFactory= New Activemqconnectionfactory(Activemqconnection.Default_user, Activemqconnection.Default_password,"tcp://localhost:61616");
ConnectionConnection=ConnectionFactory.CreateConnection();
Connection.Start();
SessionSession=Connection.CreateSession(Boolean.TRUE,
Session.Auto_acknowledge);
DestinationDestination=Session.Createqueue(QueueName);
MessageProducerProducer=Session.Createproducer(Destination);
For (IntI= 0;I< 3;I++) {
TextMessageMessage=Session.Createtextmessage("Count"+New Date().GetTime());
Thread.Sleep(1000);
Sending messages through message producers
System.Out.println ( "send Message" +i+ new date ());
Producer.message }
Session. ();
Session. ();
Connection. ();
}
}
} /span>
Sender's main function is to send a message, receiver's main function is to accept the message, and display the content of the message, here to explain in detail the way to accept the message:
(1) The first method accepts a message using consumer.receive () or consumer.receive (int timeout), and the recipient of the message waits until a message arrives or times out.
In fact, the first method and the third method of acceptance principle, the difference is the first to know to accept the number of messages, accept the message, the manual relationship connection. The third one does not know how many data to accept, so use the while (true) dead loop to accept the message directly.
(2) The second method: the message consumer registers a messagelistener, when the message arrives, will callback its onmessage () method.
It should be noted here that you register to complete the MessageListener, do not close the connection session.close (), and Connection.close (); Because you just registered to complete the listener, you close the connection, you will not receive the message, So there is no processing in the listener. (This problem can make me cry, have a long day, just to understand)
See the information on the ACTIVEMQ page that shows the queue
Name is the queue name
Number of Pending Messages is how many messages in the queue are waiting out of the queue
Number of consumers is a queue of how many consumers
Messages enqueued is the total number of messages in the queue
Messages dequeued is the number of messages in the queue that have been queued
Exceptions encountered in development:
(1) javax.jms.JMSException:Could not connect to broker url:tcp://localhost:61616. Reason:java.net.ConnectException:Connection Refused:connect
The connection was rejected because the ACTIVEMQ server was not turned on.
WORKAROUND: Open ACTIVEMQ Server, please refer to "Activemq run up "
ACTIVEMQ sending messages and receiving messages