JMS ACTIVEMQ Learning

Source: Internet
Author: User
Tags reserved

This article was reproduced from: http://somebody-hjh.iteye.com/blog/726050
There are also some related tutorials address: http://wenku.baidu.com/view/c4f65dca4afe04a1b071dee4.html
The little demo you wrote. Download Address: http://download.csdn.net/detail/u012049463/6630691

A News

Message classification:
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.

The pros and cons of synchronous asynchrony:
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 calls 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.

Talk about Async:
Asynchronous message, like a mailbox system, we put the letter into the mail bucket, the postman will according to the above address, sent to the place where the letter to go. 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.

JMS Specification:
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. JMSDOMAIN: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.

Jmsdomain (PTP, pub/sub):
PTP (point-to-point, the point-to-point message transfer model) is implemented through a first-in, in-out queue. Many people misunderstand this PTP concept, so-called point-to-point does not mean that producers and consumers have only one, but that a message can only be consumed by a consumer. As shown below, we can see that one or more producers send a message, 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.
PTP is shown in the following figure:



In the PUB/SUB message model, a message generated by a producer is broadcast to all subscribers who have subscribed to the topic. 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:
public class Queuesender {

        public static void Main (string[] args) throws jmsexception{  
            ConnectionFactory factory=new Activemqconnectionfactory ("tcp://localhost:61616");//This is a simple, activemq-dependent JMS implementation. 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 ());  
            Queue queue=new activemqqueue ("Queue.somebody");//Ibid, here relies on the JMS implementation of ACTIVEMQ, in reality can use Jndi lookup method to obtain the queue.  
            messageproducer producer=session.createproducer (queue);  
            Producer.send (message);  
            Session.close ();  
            Connection.close ();  
        }  
    }  

Receiving end:
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");  
                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:
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

Used to correlate multiple messages, such as the need to reply to a message, you can set the Jmscorrelationid to the Jmsmessageid of the received message

Client

Jmsreplyto

The message producer needs the consumer's reply, Jsmreplyto is a destination, indicates the destination that needs to reply, the consumer can disregard this parameter

Client

Jmstype

Message body structure, related to the message provider

Client

Jmsredelivered

This parameter is true to indicate that the message was resent

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.

References

Note: The following reliability does not include the inability of the JMS server due to resource relationships, resulting in messages not being persisted (this type of unreliable should be the limit of resources and processing power caused by the JMS provider or hardware, and should be addressed by the management staff). Also does not include messages due to the loss of destruction caused by timeouts.

The

Message send side

Message receiver

Reliability and factors

Persistent

Queue receiver/durable subscriber

Consume once and spend only once. Reliability is best, but server resources are more expensive.

Persistent

non-durable subscriber

Up to consume one Times. 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

is consumed at most once. This is due to server downtime resulting in message loss

non_persistent

Non-durable subscriber

/td>

Is consumed at most once. This is due to the server's outage causing the message to be lost, or because of 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? Sessionsession=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

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.