Java Message Service Basics

Source: Internet
Author: User
Tags publish subscribe

A major obstacle to information exchange between different systems is how to achieve consistency in precise data exchange and formatting. Java Message Service (JMS) solves this problem by providing a method for interacting with J2EE applications or traditional systems.

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, this frees developers.

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, persistent subscription can provide flexibility and reliability through queues, while still allowing messages to be 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 created by connection factory and located through JNDI lookup.

// Obtain queueconnectionfactory for P2P
Queueconnectionfactory = queueconnectionfactory ();
Context messaging = new initialcontext ();
Queueconnectionfactory = (queueconnectionfactory)
Messaging. Lookup ("queueconnectionfactory ");

// Obtain topicconnectionfactory For pub/sub
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.

· The client_acknowledge client receives a message and calls the confirmation method for this message.

· The dups_ OK _acknowledge option command session is "lazy" to confirm message transmission. It can be thought that this will cause some replication messages transmitted by the message provider to fail. This validation method should only be used when the message consumer program can tolerate the existence of potential duplicate 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 shipped using the mechanism of temporary transfer. 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 a non-persistent message is used, it may reduce the internal and memory required, and this transmission mode is used only when you do not need to receive all messages.

Although the JMS specification does not require the JMS supplier to implement the priority line of a message, it needs to deliver a faster message than a normal message. JMS defines the priority route level from 0 to 9. 0 is the lowest priority 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

This code snippet has two message models. The ing delivery method is persistent, the priority is the accelerated type, and the life cycle is 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 messagelistener interfaces using messageconsumer. 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 the message
}
}

When we create queuereceiver and topicsubscriber, we pass the message selector string:

 

// P2P queuereceiver
Queuereceiver receiver;
Scheduler = session. createreceiver (queue, selector );

// Pub-sub topicsubscriber
Topicsubscriber subscriber;
Subscriber = session. createsubscriber (topic, selector );

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 method used to extract or open the message content. 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 );

// Implement the necessary program logic for Message Processing
}

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 (); // P2P

Other J2EE components-servlet or EJB-can be used as message producers. However, they may only be able to perform synchronization operations, which may be determined by the nature of their request-response. Although XML is not currently a supported message type, sending an XML file and creating a text message and adding an XML file to a message is as easy as loading, data is transmitted in a non-proprietary manner. It is worth noting that some JMS vendors have provided available XML message types. However, non-standard message types may cause portability issues.

 

String reportdata; // The reportdata content is an XML document.
Textmessage message;

Message = session. createtextmessage ();
Message. settext (reportdata );

The message-driven component (MDB) is an asynchronous message consumption program called by the container when the message arrives. Unlike entity and session EJB, MDB does not have local and remote interfaces and is 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. For 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 implements the 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.

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.