Activemq Share (a) Introduction to JMS

Source: Internet
Author: User
Tags reserved
It programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary.


I. Overview

Message, that is, the messages. Communicate information between people through messages. Words, eyes, body movements can be seen as the message body. Of course, we often use the mail, text messages. Computer systems are also run by messages. The execution of each instruction, the passing of each packet. Collaboration between software systems is no exception, and the message tells the system how to collaborate. The event-handling mechanism is also the process of message delivery. Messages are everywhere.

Messages are divided into synchronous and asynchronous messages. The synchronization message needs to be suspended until it returns or times out before it receives a return from the other party. An asynchronous message only needs to send a message, without immediate feedback from the other system.

Synchronous messages such as Java RPC calls, synchronous calls rely on the callee, if the callee fails or the network error, then the program can not continue to execute, resulting in a system weakest link depends on the other system. When multiple systems are coupled together by synchronous invocation, reliability depends on the weakest party system. asynchronous invocation can enhance the robustness of a system. Of course, not all cases are suitable for asynchronous invocation, or that sentence, can be asynchronous place, as far as possible asynchronous.

Asynchronous message, like a mailbox system, we put the letter into the mail bucket, the postman will have the above address, sent to the letter to go to the place. The mailbox and letter formats are defined by the Post office, such as a mailbox that needs a cut-off message, an address, a zip code, and so on. The specific processing and production of these mailboxes are to be completed by their respective manufacturers.
In the Java messaging World, we also have something called message middleware to provide such a service. The sending of messages, the consumption interface, the format of the message body are defined by JMS, and the concrete implementation is implemented by the various message middleware vendors. JMS is a specification of sun's messaging middleware. Plays a pivotal role in the Java domain. Previous message interactions, each implementing a set of formats, as people in a country communicate in different dialects to people from different provinces. Our communication cost has been reduced since the standard of Putonghua. This is just like the JMS specification's role in the entire Java messaging domain.

ii. introduction of JMS

The JMS1.1 specification defines concepts and a set of APIs that allow us to write message codes without relying on the specific implementations of each vendor in the process of using the message system. This code is well-ported because it does not rely on specific vendor implementations.
JMS1.1 defines some of the concepts:
1. JMS Client: Java system for receiving or sending messages
2. JMS message body: The message body sent between systems
3. JMS Provider: JMS Specification Implementation Vendor
4. JMS Management object: Pre-configured JMS object for JMS client. such as connectionfactory and JMS server Connection factory, Destination receive and send message destination address, etc.
5. JMS DOMAIN:JMS defines two domain models, one is PTP (point-to-point), which is a point-to-point message transmission model, and the Pub/sub (Publish-subscribe) is a publish-subscribe model.
PTP is implemented through a first-in, FIFO queue. Many people misunderstand this PTP concept, so-called point-to-point does not mean that producers and consumers have only one. PTP is shown in the following figure:



As we can see, one or more producers send messages, the message M2 arrives in the queue first, and then the M1 is issued, and together in a FIFO queue. The consumer also exists one or more, consuming the messages in the queue. But the message was consumed by a random consumer and consumed only once.

In the PUB/SUB message model, messages are broadcast to all subscribers. The following figure:




JMS1.1 defines the following interfaces:


JMS Universal Interface JMS PTP Interface JMS Pub/sub Interface Describe
ConnectionFactory Queueconnectionfactory Topicconnectionfactory Create a connection to the JMS service
Connection Queueconnection Topicconnection A connection to the JMS service to create a session
Destination Queue Topic Queue and topic can be considered as a destination to send the destination of receiving messages
Session Queuesession Topicsession Session
MessageProducer Queuesender Topicpublisher Message sender
Messageconsumer QueueReceiver, Queuebrowser TopicSubscriber Message Recipients/Visitors/Subscribers



The interface relationships are as follows:





You can see the standard process for sending a JMS app: Create a connection factory > Create a connection > Create a session> Create a sender > Create a message body > send a message to destination (queue or topic).

The receiving side is: Create Connection factory > Create connection > Create session> Create recipient > Create Message Listener Listen for a destination message > get message and Execute business logic

The following shows the encoding template for JMS:

Send side:

    Java code   public class queuesender {            public static void main (String[] args)  throws  jmsexception{                Connectionfactory factory=new activemqconnectionfactory ("tcp://localhost:61616");//Here for simplicity, A JMS implementation that relies on ACTIVEMQ. In a real-world program, you can find factory through Jndi lookups, which completely avoids associating specific JMS implementations. and has the greatest portability.                connection connection =factory.createconnection ();                session session=connection.createsession (False,session.auto_acknowledge);                message message=session.createtextmessage (" hello world! " +new date (). GetTime ());       &Nbsp;       queue queue=new activemqqueue ("Queue.somebody");//Ibid., This relies on the JMS implementation of ACTIVEMQ, in which a jndi lookup can be used to obtain a queue.                MessageProducer  Producer=session.createproducer (queue);                producer.send (message);                session.close ();                connection.close ();           }        }  

Receiving end:
        Java code   public class queuereceiver {               public static void main (String[] args)  throws JMSException{                    ConnectionFactory factory=new  Activemqconnectionfactory ("tcp://localhost:61616");                    connection connection=factory.createconnection ();                     Session session=connection.createsession (False,session.auto_acknowledge);                    Queue queue=new  Activemqqueue ("Queue.somebody");  &nBsp                  Messageconsumer receiver=session.createconsumer (queue);//Create two receivers while consuming the same queue message. The messages in the queue are distributed and distributed only once to the only consumer.                     Messageconsumer receiver2=session.createconsumer (queue);                    receiver.setmessagelistener (new  Queuemessagelistener ("1"));                    receiver2.setmessagelistener (New queuemessagelistener ("2"));                    Connection.start ();               }            }   

Message listener:
Java code public class Queuemessagelistener implements messagelistener{private String num;           Public queuemessagelistener (String num) {super ();       This.num=num;       } public Queuemessagelistener () {super ();       } public void OnMessage (Message message) {SYSTEM.OUT.PRINTLN (message.tostring () +num); }

After we have installed APACHEMQ, we can test the execution of these classes and observe the execution process by starting the local MQ service. We can find that messages are consumed only once, and the JMS provider must ensure that a message is not consumed repeatedly, and certainly not lost.

In PTP, after we establish a queue, if no consumer is connected to the queue, messages sent by the message producer will be blocked in the queue until consumers consume it. If the consumer fails, no longer connected to the queue, the message will be saved in the queue, waiting for the next consumer to connect, and then consumption. Under the Pub/sub model, if the consumer fails, then all messages will not be reserved, and the next time the connection is connected, only the messages sent by the producer can be consumed at this point. JMS then defines another subscriber, called Durable Subscription (persistent subscriber), who, after the first connection to the topic, registers the topic message, which retains the message if the consumer is unavailable, and after it is connected again topic, Re-tweet the message to the consumer.

After understanding the two message models in JMS, let's say the message physique in JMS. JMS set the message body as three Parts 1) Head message header information 2) Properties message property value 3) Body message content. As shown in the following illustration:



The meaning is broadly explained as follows:

Header type Describe Set party
Jmsdestination Describe the destination to which the message was sent Set in the Send method
Jmsdeliverymode Non_persistent non-persistent indicates that the message was sent to the JMS messaging server, persisted in memory, persisted, and persisted after the persistent persisted message was sent to the JMS messaging server. To guarantee message loss due to message server topology Set in Send method
Jmsexpiration Message expiration time. When a consumer sends a message, it can set the time-to-live time of the message, such as Producer.settimetolive (10000), which remains in the Jmsexpiration field of the message after the message is sent. If the message is not consumed during the specified time period, the message is discarded. Set in the Send method
Jmspriority Message priority, JMS divides the message into 10 levels, 0-4 is the normal priority, 5-9 accelerates the priority, and the default message priority in ACTIVEMQ is 4 Set in the Send method
Jmsmessageid Message uniqueness ID, must be prefixed with "ID:" Set in the Send method
Jmstimestamp Message send time, indicating the point at which the message was sent, not the delivery time Set in the Send method
Jmscorrelationid Client
Jmsreplyto Client
Jmstype Client
Jmsredelivered JMS Provider
Property value Meaning
Properties
Message body Meaning
Body The message body is divided into 1:streammessage2:mapmessage 3:textmessage 4:objectmessage 5:bytesmessage


talk about message reliability again

In the above, referring to the message definition, there is a field jmsdeliverymode to indicate what the JMS provider should do with the message after it is sent. Persistent (persisted) messages are persisted in the JMS server. If the receiver is in point-to-point queue mode or durable Subscription (persistent subscriber) mode, then the message is guaranteed to be successfully received only once. Non_persistent (non-persisted) messages are lost when the JMS server is shut down or down. The following reliability tables are listed for reference, based on the method used by the sending and receiving terminals.

Note: The following reliability does not include unreliable sources such as the inability of the JMS server to persist due to resource relationships, which should be the limit of resources and processing power caused by JMS providers or hardware, and should be addressed by managers. Also does not include messages due to the loss of destruction caused by timeouts.
Message Sending side Message Receiving End Reliability and factors
Persistent Queue Receiver/durable Subscriber Consume once and consume only once. Reliability is best, but server resources are more expensive.
Persistent Non-durable Subscriber Consume at most once. This is due to the fact that Non-durable Subscriber decides that if a consumer outage or other problem causes a disconnect with the JMS server, a series of messages will not be reserved for the next time the JMS server is connected.
Non_persistent Queue Receiver/durable Subscriber Consume at most once. This is due to server downtime resulting in message loss
Non_persistent Non-durable Subscriber Consume at most once. This is due to server downtime resulting in message loss, or possibly due to the nature of the Non-durable subscriber


notification confirmation for a message
After the client receives the message, how does the JMS service effectively verify that the message has been received by the client? Session session=connection.createsession (False,session.auto_acknowledge); This code creates a non-transactional session and uses the Auto_ The acknowledge method notifies the JMS server. If a transactional session is used, the notification will accompany the commit/rollback of the session and send a notification. There are three ways to notify us when we use a non-transactional session.
Notification method Effect
Dups_ok_acknowledge Session delay notification. If the JMS server goes down, it can cause duplicate messages. The program must ensure that duplicate messages are processed without causing confusion in the program logic.
Auto_acknowledge Automatically notifies you when the receive or MessageListener method returns successfully.
Client_acknowledge Acknowledge method notification for client invoke messages




JMS is briefly introduced here, please refer to the JMS1.1 specification for more details. About ACTIVEMQ article please continue to follow ACTIVEMQ share (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.