Introduction to JMS and ACTIVEMQ combat _JMS

Source: Internet
Author: User
1. JMS Architecture

The Java Messaging Service (Java message Services, referred to as JMS) is a neutral API for developers accessing the enterprise messaging system. The Enterprise messaging system can assist the application software to interact with the message over the network. The role that JMS plays in this is similar to JDBC, as JDBC provides a set of public api,jms to access a variety of relational databases and also provides an enterprise messaging system that is independent of specific vendors.
Applications that use JMS are called JMS clients, and messaging systems that handle message routing and delivery are called JMS Provider, while JMS applications are business systems consisting of multiple JMS clients and a JMS Provider. The JMS client that sends the message is called the producer (producer), and the JMS client that receives the message is called the consumer (consumer). The same JMS client can be either a producer or a consumer.
The programming process for JMS is simple: Application A sends a message to a target (destination) of the message server (i.e., the JMS Provider), and the message server forwards the message to application B. Because application A and application B have no direct code connection, both implementations understand me. The following figure:

The center of the messaging system is the message. A message consists of three parts: the composition of the messages is 1. Heads (head)

Each JMS message must have a message header. The header field contains values for routing and identifying messages. You can set the value of a message header in several ways:
A. Automatically set by a JMS provider during the generation or delivery of a message
B. Set by producer clients by the settings specified when creating the message producer
C. Each message is set to 2 by the producer client. Properties (property)

A message can contain an optional header field called a property. They are made in the form of attribute names and attribute value pairs. You can extend a property as a message header, which can include information such as the process in which the data was created, when the data was created, and the structure of each piece of data. The JMS provider can also add properties that affect message handling, such as whether the message should be compressed or how to discard the message at the end of the message lifecycle. 3. Subject (body)

Contains the content to send to the receiving application. Each message interface is specific to the type of content it supports. JMS provides their respective message types for different types of content, but all messages are derived from the message interface.
Streammessage a message in a body that contains a Java primitive value stream. Its fill and read are in order.
Mapmessage a message that contains a set of key-value pairs in a body. No entry order is defined.
TextMessage a message in a body that contains a Java string (for example, an XML message).
ObjectMessage a message that contains a serialized Java object in a body.
Bytesmessage a message in a body that contains a sequential byte stream.
For example: Mapmessage message Format

mapmessage={  
    header={...  
        standard headers  
        ... CORRELATIONID={123-00001}  
    }  
    properties={  
        accountid={integer:1234}  
    }  
    fields={  
        name={ String:mark}  
        age={integer:47}}}   
  
Delivery model for messages

JMS supports two messaging models: point-to-point (point-to-point, PTP), and publish/subscribe (Publish/subscribe, abbreviated PUB/SUB). The two messaging models are very similar, but have the following differences:
A. The PTP Messaging model provides a way for a message to be passed between a receiver.
B. pub/sub messaging model allows a message to be passed to multiple receivers
Each model is implemented by extending the common base class. For example: Javax.jms.Queue and Javax.jms.Topic are both extended from javax.jms.Destination classes. 1. Point to Point Message delivery

With a point-to-point messaging model, an application can send messages to another application. In this delivery model, the target type is a queue. The message is first routed to the queue target, and then the message is routed from the modified queue to a consumer listening to the queue, as shown in the following figure:

A queue can associate multiple queue senders and receivers, but a message is passed only to one receiver. If more than one receiver is listening to messages on the queue, the JMS provider determines which recipient accepts the next message based on the "first-comer priority" principle. If no receiver is listening on the queue, the message remains in the queue until the receiver connects to the queue. This message-passing model is a model of pull or polling in the traditional sense. In this column model, the message is not automatically driven to the client, but is requested by the client from the queue. 2. Publish/Subscribe Message delivery

Through the Publish/Subscribe messaging model, an application can send a message to multiple receivers. In this transfer model, the target type is the subject. The message is first routed to the subject target and then sent to all or consumers who have subscribed to the topic. The following figure:

Theme goals also support long-term subscriptions. A long term subscription indicates that the consumer has registered the subject target, but the consumer can be inactive when the message arrives at the destination. The message will be received when the consumer is again active. If the consumer does not register for a subject target, the topic retains only messages for inactive consumers who have registered long-term subscriptions. Unlike the PTP message delivery model, the Pub/sub messaging model allows multiple topic subscribers to receive the same message. JMS retains the message until all the subject subscribers receive the message. The PUB/SUB message delivery model is basically a push model. In this model, messages are automatically broadcast, and consumers do not have to get new messages through unsolicited requests or by polling for topics.

In both of the above messaging models, we need to define the message producer and consumer, and the producer sends the message to a destination address (destination) in the JMS provider, where the message is sent from the destination address to the consumer. Consumers can receive messages synchronously or asynchronously, in general, the execution and scalability of asynchronous messaging consumers are better than the synchronous message recipients, as reflected in the following:
1. The network traffic created by the asynchronous message receiver is relatively small. One-way to the east message and make it through the pipe into the message listener. Pipeline operations support the aggregation of multiple messages into one network call.
2. Asynchronous message recipients use fewer threads. Asynchronous message receivers do not use threads during inactivity. The synchronization message receiver uses a thread during the receive call, and the resulting thread may remain idle for a long time, especially if the blocking timeout is specified in the call.
3. For application code running on a server, it is almost always best to use an asynchronous message receiver, especially through message-driven beans. Using an asynchronous message receiver prevents application code from performing blocking operations on the server. Blocking operations are idle on the server's thread and can even cause deadlocks. Deadlock occurs when all threads are used by the blocking operation. This operation will never stop blocking if there is no free thread to handle the action required to unlock the blocking operation itself. 2. JMS Provider (ActiveMQ) features and advantages to achieve JMS1.1 specifications, support j2ee1.4 above. Enables multiple-language clients (Java, C, C + +, Ajax, ActionScript, and so on) with any JVM and most web containers (ActiveMQ works great the Any JVM) to support a variety of protocols (stomp, Openwire, REST) Good Spring support (ActiveMQ has great spring Support) is fast, 10 times times jbossmq (ActiveMQ is very fast; Often 10x faster than JBOSSMQ) compared with OPENJMS, JBOSSMQ, and other open source JMS provider, ACTIVEMQ has the support of Apache, the advantages of sustainable development is significantly more than 1 of the queue and topic. The JMS queue performs the load balancer semantics

A message can only be received by a consumer. If there is no consumer available when the message is sent, it is said to be saved until the consumer that can handle it is available. If a consumer receives a message and does not respond to it, it will be transferred to another consumer. A queue can have many consumer and load-balanced in multiple consumer available.
2. Topic implements publish and subscribe semantics
When a message is publish, he will send it to all interested subscribers, so 0 to multiple subscriber will receive a copy of the message. However, when the message agent receives a message, only the Subscriber that activates the subscription can obtain a copy of the message.
3. Corresponding two message modes respectively
Point-to-Point (point-to-point), Publisher/subscriber model (publisher/subscriber)
which has nondurable subscription in Publicher/subscriber mode ( Non-persistent subscriptions) and durable subscription (persistent subscriptions) are two ways to handle messages.
Point-to-Point (point-to-point) message mode development process 1. Producer (producer) development process 1.1 Create Connection
Create a JMS Connection based on Url,user and password.  
activemqconnectionfactory connectionfactory   =   new activemqconnectionfactory (user, password, url);  
Connection = Connectionfactory.createconnection ();  
Connection.start ();  
1.2 Creating a session
/** creates a session on the basis of connection and sets whether to support transaction acknowledge identities. 
Auto_acknowledge: Automatic confirmation mode. Once the recipient application's method call returns from the processing message, the Session object confirms the receipt of the message.  
Client_acknowledge: Client confirmation mode. The session object relies on the application to invoke a acknowledge () method on the received message. Once this method is invoked, the session confirms all incoming messages after the last acknowledgment. This pattern allows an application to receive, process, and confirm a batch of messages with a single call. Note: In the admin console, if the acknowledge Policy (confirmation policy) attribute of the connection factory is set to "Previous" (in advance), but you want to confirm all received messages for a given session, then use the last message to invoke the acknowledge () method.  
Dups_ok_acknowledge: Allows the confirmation mode of the replica. Once the recipient application's method call returns from the processing message, the Session object confirms the receipt of the message, and allows duplicate acknowledgments. This pattern works well when you need to consider resource usage. Note: If your application is unable to handle duplicate messages, you should avoid using this pattern. If the initialization attempt to send a message fails, then a duplicate message can be sent back. 
•  session_transacted**/Session Session  
= Connection.createsession (  
transacted, Session.auto_acknowledge);  
1.3 Creating Destination objects
You need to specify their corresponding subject (subject) name, and producer and consumer will send/receive the corresponding message  
if (topic) {  
    destination = by subject. Session.createtopic (subject);  
} else {  
    destination = Session.createqueue (subject);  
}  
1.4 Creating MessageProducer
Creates a MessageProducer object based on destination and sets its persistent mode.   
messageproducer producer = session.createproducer (destination);  
if (persistent) {  
      producer.setdeliverymode (deliverymode.persistent);  
} else {  
      Producer.setdeliverymode (deliverymode.non_persistent);  
}  
if (timetolive!= 0) {  
       producer.settimetolive (timetolive);  
}   
1.5 Sending messages to queues (queue)
Encapsulates the TextMessage message and sends the message using the MessageProducer send method.  
TextMessage message = Session.createtextmessage ("Createmessagetext");  
Producer.send (message);  
2. Consumer (consumer) development Process 2.1 implementation MessageListener interface
The consumer class must implement the MessageListener interface and then listen for message arrival processing in the OnMessage method.  
2.2 Creating connection
Create a JMS Connection based on Url,user and password, and if it is durable mode, you need to set a Connection for ClientID.  
activemqconnectionfactory connectionfactory = new activemqconnectionfactory (user, password, url);  
Connection Connection = Connectionfactory.createconnection ();  
if (durable && clientId!= null && clientid.length () > 0 &&! " Null ". Equals (ClientId)) {  
      connection.setclientid (clientId);  
}  
Connection.setexceptionlistener (this);  
Connection.start ();  
2.3 Creating sessions and destination
Similar to the product  
2.4 Create Replayproducer "optional"
Can be used to send message processing results to producer.   
replyproducer = Session.createproducer (null);  
Replyproducer.setdeliverymode (deliverymode.non_persistent);
2.5 Creating Messageconsumer
Creates a Messageconsumer object based on destination.  
Messageconsumer consumer = null;  
If (durable && topic) {  
     consumer = session.createdurablesubscriber ((topic) destination, consumername);  
else {  
     consumer = session.createconsumer (destination);  
}
2.6 Consumption Message
In the OnMessage () method, the message received by producer is processed and can be replyproducer feedback to producer   
if (Message.getjmsreplyto ()!= null) {   
    Replyproducer.send (Message.getjmsreplyto (),   
    session.createtextmessage ("Reply:" + Message.getjmsmessageid ());   
}    

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.