Introduction to JMS

Source: Internet
Author: User
Tags publish subscribe sub domain
Java Message Service (JMS) is a set of Java application interfaces (Java APIs) that provide services for creating, sending, receiving, and reading messages. The jms api designed by Sun and its partners defines a set of common application interfaces and corresponding syntaxes so that Java programs can communicate with other message components.

JMS is a vendor-independent API used to access the message sending and receiving system. It is similar to JDBC (Java database connectivity): Here, JDBC is an API that can be used to access many different relational databases, while JMS provides access methods that are also independent of vendors, to access the message sending and receiving service. Many vendors currently support JMS, including IBM MQSeries, BEA's WebLogic JMS service, and progress's sonicmq. These are just a few examples.
JMS enables you to send messages from one JMS client to another JML client through the message sending and receiving service (sometimes called a message broker or router. A message is a type object in JMS. It consists of a header and a message body. The header consists of route information and metadata groups related to the message.
. The message body carries the data or load of the application. Based on the type of the payload, messages can be divided into several types, which carry: simple text
(Textmessage), serializable object (objectmessage), property set (mapmessage), byte stream
(Bytesmessage), the original value stream (streammessage), and messages without a payload ).

The message sending and receiving system is asynchronous, that is, the JMS client can send messages without waiting for a response. We can see that this is completely different from RPC-based (remote process-based) systems, such as EJB 1.1, CORBA, and Java RMI.
. In the RPC
The client calls a method of a distributed object on the server. The client is blocked before a method call is returned. The client must wait until the method call ends before executing the next command. In
In JMS, the client sends messages to a virtual channel (topic or Queue), while other JMS clients subscribe or listen to this virtual channel. When JMS
When the client sends a message, it does not wait for a response. It executes the sending operation and then continues to execute the next command. Messages may eventually be forwarded to one or more clients, which do not need to respond.

 
The set of common interfaces of JMS sends or receives messages asynchronously. Receiving messages in asynchronous mode is obviously the best choice for clients that use intermittent network connections, such as mobile phones and PDAs. In addition,
JMS adopts a loose combination method to integrate enterprise systems. Its main purpose is to create enterprise-level applications that can use cross-platform data information and can be transplanted, and free up development manpower.

Java Message Service supports two message models: point-to-point (P2P) and publish subscribe messaging (pub/Sub ). The JMS specification does not require suppliers to support both message models at the same time, but developers should be familiar with the advantages and disadvantages of these two message models.

The P2P message model is used when messages are transmitted between points and points. If the application developer wants to process each message, the P2P message model should be used. Unlike the pub/sub message model, P2P messages can always be sent to a specified location.

The pub/sub model is used for one or more message broadcasts. If the reliability of message transmission is acceptable to a certain extent, application developers can also use the pub/sub message model. In other words, it applies to situations where all message consumption programs do not require the ability to receive all information or message consumption programs do not want to receive any message.

 
JMS allows you to create a persistent subscription to simplify the time correlation. A message can be received even if the message subscription is not activated. In addition, using persistent subscription can also provide flexibility and reliability through queues, while still allowing
Messages are sent to many recipients. Topic subscriber topic subscriber =
Topicsession. createdurablesubscriber (topic, subscriptionname );
The connection object indicates the connection to any of the two message models. The server and client objects must manage the status of the created JMS connection. The connection is composed
The connection factory is created and located through the JNDI lookup. // Obtain queueconnectionfactory for P2P
Queueconnectionfactory = queueconnectionfactory (); Context messaging =
New initialcontext (); queueconnectionfactory = (queueconnectionfactory)
Messaging. Lookup ("queueconnectionfactory"); // obtain
Topicconnectionfactory topicconnectonfactory topicconnectionfactory;
Context messaging = new initialcontext (); topicconnectionfactory =
(Topicconnectionfactory) messaging. Lookup ("topicconnectionfactory ");
Note: The code for P2P is very similar to that for publishsubscribe.

If the session is marked as transactional, the confirmation message is automatically processed through confirmation and correction. If the session is not marked as transactional, you have three options for message validation.

· Auto_acknowledge session will automatically confirm to receive a message.

· Client_acknowledge Client
The confirmation method of the message is called. · Dups_ OK _acknowledge
The command session "lazy" is used to confirm message transmission, which may lead to errors in copying messages transmitted by the message provider. This validation method should only be used by the message consumer program.
It can tolerate the existence of potential copy messages. Queuesession =
Queueconnection. createqueuesession (false,
Session. auto_acknowledge); // P2P topicsession =
Topicconnection. createtopicsession (false, session. auto_acknowledge );
// Pub-sub

Note: In this example, a session is created from the link. The non-value indicates that the session is non-transactional, and the session will automatically confirm to receive a message.

 
JMS currently has two ways to transmit messages. Messages marked as non_persistent can be shipped at most once, while messages marked as persistent will be temporarily stored before being transferred.
Shipping. If a JMS service is offline, persistent messages will not be lost, but will not be transmitted until the service is restored online. Therefore, the default message transmission method is non-persistent. Even if non-persistent
Sexual messages may reduce internal and memory requirements, and this transmission method is only used when you do not need to receive all messages.

 
Although
The JMS specification does not require the JMS supplier to implement the priority route of messages, but it needs to deliver accelerated messages with priority over normal messages. JMS defines the priority route level from 0 to 9, and 0 is the lowest
And 9 is the highest. What's more, 0 to 4 represents the variation of the normal priority, and 5 to 9 represents the variation of the accelerated priority. For example:
Topicpublisher. Publish (message, deliverymode. Persistent, 8, 10000 );
// Pub-sub or queuesender. Send (message, deliverymode. Persistent, 8,
10000); // P2P code snippet. There are two message models. The ing delivery method is persistent, with a priority of accelerated type and a lifecycle of 10000 (measured in milliseconds ). If the life cycle is set to zero, the message will never expire. It is useful to set a life cycle when a message requires a time limit or it becomes invalid.

JMS defines five different message body formats and call message types. It allows you to send and receive data in different forms and provides compatibility of existing message formats.

· Streammessage -- data stream of the original Java Value

· Mapmessage -- a set of name-value pairs

· Textmessage -- A String object

· Objectmessage -- A serialized Java object

· Bytesmessage-An uninterpreted byte data stream

 
The JMS application interface provides methods for creating messages of each type and setting loads. For example, to create and send a textmessage instance in a queue, you can use the following statements:
Textmessage message = queuesession. createtextmessage ();
Message. settext (textmsg );
To receive messages asynchronously, you must create a message listener and register one or more JMS listeners that use messageconsumer.
Messagelistener interface. A session (topic or Queue) is responsible for generating certain messages that are sent to the listener using the onmessage method. Import
Javax. JMS. *; public class
Examplelistener implements messagelistener {// forcibly convert a message to textmessage format
Public void onmessage (message) {textmessage textmsg = NULL ;//
Open and process this message} when we create queuereceiver and topicsubscriber, we pass the message selector string: // P2P
Queuereceiver receiver; receiver =
Session. createreceiver (queue, selector); // pub-sub topicsubscriber
Topicsubscriber subscriber; subscriber = session. createsubscriber (topic,
Selector); In order to start message delivery, both pub/sub and P2P must call the start method.
Topicconnection. Start (); // pub-sub queueconnection. Start (); // P2P
Topicconnection. Start (); // pub-sub queueconnection. Start (); // P2P

 
When a message is captured, the message arrives as a common message object that must be forcibly converted to an appropriate message type. This is a getter used to extract or open the message content.
Method. The following code snippets use the streammessage type. Private void unpackmessage (message ){
String ename; string position; double rate; streammessage message;
Message = session. createstreammessage (); // note that the following code must be written in the order I have given
Message. writestring (ename); message. writestring (position );
Message. writedouble (rate); // The necessary program logic to process the message}

 
Stop message transmission. Both pub/sub and P2P call the stop method. Topicconnection. Start (); // pub-sub
Queueconnection. Start (); // P2P topicconnection. Start (); // pub-sub
Queueconnection. start (); // other P2P J2EE components-servlet or EJB-can be used as message producers; however, they can only be synchronized, this may be determined by the nature of their request-response. Although XML is not currently a supported message type, send an XML file and
Creating a text message and adding an XML file to a message are as simple as uploading data in a non-proprietary manner. It is worth noting that some JMS suppliers have provided available
XML Message type. However, non-standard message types may cause portability issues. String reportdata; // The reportdata content is XML.
Textmessage message; message = session. createtextmessage ();
Message. settext (reportdata );

Message driver group
MDB is an asynchronous message consumption program called by the container when a message arrives. And entity and session
Different from ejbs, MDB does not have local and remote interfaces and are anonymous; they are invisible to customers. MDB is a part of the JMS system and serves as a consumer to implement commercial logic programs on the server.
A client program may use JNDI to locate a JMS associated with MDB. Example: context initialcontext = new
Initialcontext (); queue reportinfoqueue =
(Javax. JMS. Queue) initialcontext. Lookup
("Java: COMP/ENV/JMS/reportinfoqueue"); MDB is composed of bean classes and corresponding XML deployment descriptors. Bean
Class implementation messagedrivebean interface: Import javax. EJB. *; import JMS. Message. *; Public
Interface messagedrivebean {public void ejbcreate (); Public void
Ejbremove (); Public void setmessagedrivencontext (messagedrivencontext
CTX);} message listener interface: Import javax. JMS. *; public interface messagelistener {
Public void onmessage ();}

Deployment descriptor
<! Doctype EJB-jar public "-// Sun Microsystems, Inc. // DTD Enterprise
JavaBeans 2.0 // en "" http://java.sun.com/j2ee/dtds/ejb-jar_2_0.dtd ">
<EJB-jar> <enterprise-beans> <message-driven> <EJB-Name> MDB </EJB-Name>
<EJB-class> MDB </EJB-class>
<Transaction-type> container </transaction-type>
<Message-driven-destination>
<JMS-destination-type> javax. JMS. Queue </JMS-destination-type>
</Message-driven-destination> <security-identity>
<Run-as-specified-identity> <role-Name> everyone </role-Name>
</Run-as-specified-identity> </security-identity> </message-driven>
</Enterprise-beans> </EJB-jar>

Now that we have some basic JMS knowledge, what can we do with JMS? Everything works.

For example, systems used for sales, inventory, customer service, and account processing. The systems between these departments are likely to have existed for a long time. These processes require moving transactions to the system, which is not a small task. This is where the message service is applicable.

When the salesperson completes the sales, a message is sent to the inventory system. Once the order message is sent to the delivery personnel, the order can be shipped. When the order is successfully delivered, the system will notify the customer service and accounting system that the order has been successfully traded. All corresponding subsystems are automatically updated based on received messages.

Generally, JMS is not used to integrate a system, but to integrate many systems that may participate in the message-driven environment. JMS is an important tool for developing and integrating enterprise applications. Because many companies have systems integrated with the legacy systems and the newly developed systems, the use of messages is an important step to integrate the entire enterprise.

  

JMS Interface Description

JMS supports two message types: PTP and pub/sub, called PTP domain and pub/sub domain. Both of these interfaces inherit the unified JMS parent interface, the main interfaces of JMS are as follows:

 

JMS parent  Ptpdomain Pub/sub domain
Connectionfactory Queueconnectionfactory Topicconnectionfactory
Connection Queueconnection Topicconnection
Destination Queue Topic
Session Queuesession Topicsession
Messageproducer Queuesender Topicpublisher
Messageconsumer Queuereceiver, queuebrowser Topicsubscriber

The following is a brief description of these interfaces:
Connectionfactory: Connection factory, which is used by JMS to create a connection
Connection: the connection from the JMS client to the JMS provider
Destination: the destination of the message.
Session: a thread that sends or receives messages.
Messageproducer: the object created by the session object for sending messages
Messageconsumer: the object created by the session object to receive messages.

JMS message model

A jms Message consists of the following parts: Message Header, attributes, and message body.

Header)-The message header contains the recognition and route information of the message. The message header contains some standard attributes such as jmsdestination and jmsmessageid.

Message Header Set by WHO
Jmsdestination Send or publish Method
Jmsdeliverymode Send or publish Method
Jmsexpiration Send or publish Method
Jmspriority Send or publish Method
Jmsmessageid Send or publish Method
Jmstimestamp Send or publish Method
Jmscorrelationid Customer
Jmsreplyto Customer
Jmstype Customer
Jmsredelivered JMS provider


Properties)-Apart from the standard attributes defined in the message header, JMS provides a mechanism to add new attributes to the message header. These new attributes include the following:
1. attributes required by the application;
2. Some optional attributes in the message header;
3. attributes required by the JMS provider.
The standard JMS header contains the following attributes:
Jmsdestination -- message sending destination
Jmsdeliverymode -- transfer mode,
There are two modes: persistent and non_persistent.
Indicates that the message must be sent to the destination; otherwise, an application error occurs. Non_persistent
It indicates that accidental loss of the message is allowed. The two modes allow developers to find a balance between the reliability and throughput of message transmission.
Jmsmessageid uniquely identifies each message, which is generated by the JMS provider.
Jmstimestamp refers to the time when a message is submitted to the JMS provider to the time when the message is sent.
Jmscorrelationid is used to connect to another message. A typical application is to connect to the original message in the reply message.
Jmsreplyto provides the destination address of the message to be replied.
Jmsredelivered if a client receives a message with the jmsredelivered attribute set, it indicates that the client may have received the message earlier but has not signed for it (acknowledged ).
Message type identifier of jmstype.

The expiration time of the jmsexpiration message, which is equal to the timetolive value in the send method of the queuesender.
Value or the timetolive value in the publish method of topicpublisher plus the GMT of the sending time
Time Value. Jmsexpiration
If it is set to zero, the message never expires. If the message is not sent to the destination after the message expires, the message is cleared.
Jmspriority indicates the priority of a message, ranging from 0 to 9. 0-4 indicates a common message and 5-9 indicates an urgent message. JMS does not require the JMS provider to send messages in strict accordance with these ten priorities, but it must ensure that the urgent message arrives before the common message.

Body)-The jms api defines five message body formats, also known as message types. You can send and receive data in different formats and be compatible with the existing message formats. The five types are described below:

Message Type Message Body
Textmessage Java. Lang. String object, such as XML file content
Mapmessage Set of name/value pairs. The name is a string object. The value type can be any basic Java type.
Bytesmessage Byte stream
Streammessage Input and Output streams in Java
Objectmessage Serializable objects in Java
Message There is no message body, only the message header and attributes.

The following example shows how to create and send a textmessage to a queue:

 

TextMessage message = queueSession.createTextMessage(); message.setText(msg_text); // msg_text is a String queueSender.send(message);

 

The following example shows how to receive a message and convert it to a suitable Message Type:

 

Message m = queueReceiver.receive(); if (m instanceof TextMessage) { TextMessage message = (TextMessage) m; System.out.println("Reading message: " + message.getText()); } else { // Handle error }

(Source: club.169.netsprite.com; www.wxsf.net)

Message consumption

Messaging products are inherently
Asynchronous in that no fundamental timing dependency exists between
Production and the consumption of a message. However, the JMS
Specification uses this term in a more precise sense. messages can be
Consumed in either of two ways:

  • Synchronously.A subscriber or
    Receiver explicitly fetches the message from the destination by calling
    ThereceiveMethod.receiveMethod can block
    Until a message arrives or can time out if a message does not arrive
    A specified time limit.

  • Asynchronously.A client can register
    Message listenerWith a consumer. A message listener is similar
    An event listener. Whenever a message arrives at the destination, the JMS
    Provider delivers the message by calling the listener'sonMessage
    Method, which acts on the contents of the message.


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.