Getting Started with the JMS (Java Messaging Service) tutorial

Source: Internet
Author: User
Tags event listener message queue

What is the Java messaging Service

The Java Messaging Service, which is an API for asynchronous communication between two applications, provides a common set of interfaces for standard messaging protocols and messaging services, including creating, sending, reading messages, and so on, to support Java application development. In Java EE, when two applications use JMS for communication, they are not directly connected, but are connected by a common messaging service to achieve the decoupling effect, which we'll cover in detail in the next tutorial.

Why JMS is required

In Java, if the two applications are not aware of each other, and even if the two programs may be deployed on different continents, how do they send messages between them? For example, an application A is deployed in India, another application is deployed in the United States, and then whenever a triggers something, b wants to get some update information from a. Of course, it is also possible that more than one B is interested in the update of a, and there may be n B-like applications that want to get updated information from a.

In this case, Java provides the best solution-JMS, which perfectly solves the problem discussed above.

JMS also applies to event-based applications, such as chat services, which require a publishing event mechanism to send messages to all clients connected to the server. Unlike RMI, the recipient does not need to be online when sending a message. The server sends the message and then it does not, and when the client is online, it is guaranteed to receive the message sent by the server. This is a very powerful solution that can handle many of the world's most common problems today.

Advantages of JMSAsynchronous

JMS is inherently asynchronous, and when the client obtains the message, it does not need to send unsolicited requests, and the message is automatically sent to the available clients.

Reliable

The JMS guarantee message is delivered only once. Everyone has encountered a duplicate creation message problem, and JMS can help you avoid the problem.

JMS Message Delivery model

Before the JMS API appeared, most products used a "point-to-point" and "Publish/subscribe" In any way for message communication. JMS defines the specifications for these two message-sending models, which are independent of each other. Any JMS provider can implement one or both of these models, which is their own choice. The JMS specification provides a common interface to ensure that the programs we write based on the JMS API are suitable for any model.

Let's look at both of these messaging models in more detail:

Point-to-point messaging model

In a point-to-point messaging model, applications consist of message queues, senders, and receivers. Each message is sent to a special message queue that holds all messages sent to it ( in addition to messages consumed by the receiver and expired). The point-to-point message model has some features, as follows:

    • Each message has only one recipient;
    • Message senders and receivers do not have time dependencies;
    • When the message sender sends a message, the recipient program can obtain the message regardless of whether it is running;
    • When the recipient receives the message, it sends a confirmation receipt (acknowledgement).

Publish/ Subscribe message delivery model

In the Publish/Subscribe message model, the Publisher publishes a message that is passed through topic to all clients. In this model, publishers and Subscribers do not know each other, are anonymous, and can dynamically publish and subscribe to topic. Topic is primarily used to save and deliver messages, and the message is persisted until the message is passed to the client.

The Publish/Subscribe message model features are as follows:

    • A message can be passed to multiple subscribers
    • Publishers and Subscribers have time dependencies, and only when a client creates a subscription can the message be accepted, and the Subscriber remains active to receive the message.
    • To mitigate such strict time dependencies, JMS allows subscribers to create a durable subscription. This way, even if the Subscriber is not activated (running), it can receive the message from the publisher.

Receiving messages

In JMS, the receipt of a message can be used in the following two ways:

Synchronous

A message subscriber invokes the receive () method when it receives a message synchronously. In receive (), the message does not arrive or until the specified time is reached, and the method blocks until the message is available.

Asynchronous

When a message is received asynchronously, the message subscriber registers a message listener, similar to an event listener, that, as long as the message arrives, the JMS service provider will deliver the message by invoking the listener's OnMessage ().

JMS Programming Interface

The JMS application consists of the following basic modules:

    1. Management Objects (administered objects)-Connection factory (Connection factories) and destination (Destination)
    2. Connection object (Connections)
    3. Session (Sessions)
    4. Messaging Producer (message producers)
    5. Messaging consumer (message consumers)
    6. Messages Listener (Message Listeners)

JMS Management Objects

The management object (administered objects) is a preconfigured JMS object that is created by the system administrator for clients using JMS, with two managed objects:

    • Connection Factory (ConnectionFactory)
    • Destination (Destination)

These two management objects are created by the JMS system administrator by using the Application Server Management console, which is stored in the application server's Jndi namespace or the Jndi registry.

Connection Factory (ConnectionFactory)

The client connects to the JMS service provider using a connection factory object, which creates a connection between the JMS service provider and the client. The JMS client, such as the sender or recipient, searches for and obtains the connection in the Jndi namespace. With this connection, the client communicates with the destination, sending/receiving messages to the queue or topic. Let's use an example to understand how to send a message:

Queueconnectionfactory queueconnfactory = (queueconnectionfactory) initialctx.lookup ("PrimaryQCF"); Queue Purchasequeue = (queue) initialctx.lookup ("Purchase_queue"); Queue Returnqueue = (queue) initialctx.lookup ("Return_queue");
Destination (Destination)

Destination indicates the destination at which the message was sent and the source from which the client received the message. JMS uses two destinations, queues, and topics. The following code specifies a queue and topic.

Create a queue session

Queuesession ses = con.createqueuesession (false, Session.auto_acknowledge);  Get the Queue object  Queue T = (Queue) ctx.lookup ("Myqueue");  Create QueueReceiver  

Create a topic session

Topicsession ses = con.createtopicsession (false, Session.auto_acknowledge); Get the Topic object  Topic t = (Topic) ctx.lookup ("MyTopic");  Create TopicSubscriber  TopicSubscriber receiver = ses.createsubscriber (t);  
JMS Connection

The connection object encapsulates the virtual connection to the JMS provider, and if we have a ConnectionFactory object, you can use it to create a connection.

Connection Connection = Connectionfactory.createconnection ();

After you create the connection, you need to close it after the program has finished using it:

Connection.close ();
JMS Sessions (session)

Session is a single-threaded context for producing and consuming messages that can be created by message producers and message consumers.

The session object implements the session interface, which we can use to create the session after the connection is created.

Session session = Connection.createsession (false, Session.auto_acknowledge);
JMS message Producer

The message producer is created by the session and is used to send messages toward the destination. The producer realizes the MessageProducer interface, we can create the producer for the destination, the queue or the topic;

MessageProducer producer = Session.createproducer (dest); MessageProducer producer = Session.createproducer (queue); MessageProducer producer = session.createproducer (topic);

After you have created the message producer, you can use the Send method to send the message:

Producer.send (message);
JMS Message Consumer

The message consumer is created by the session to accept the message sent by the destination. The consumer realizes the Messageconsumer interface, we can create the consumer for the destination, the queue or the topic;

Messageconsumer consumer = Session.createconsumer (dest); Messageconsumer consumer = session.createconsumer (queue); Messageconsumer consumer = session.createconsumer (topic);
JMS Message Listener

The JMS message listener is the default event handler for the message, and he implements the MessageListener interface, which contains a OnMessage method in which you need to define the specific action after the message is reached. By calling the Setmessagelistener method we define a message listener for the specified consumer

Listener MyListener = new Listener (); Consumer.setmessagelistener (MyListener);
JMS message Structure

JMS clients use JMS messages to communicate with the system, and JMS messages are composed of three parts, although they are simple in format but very flexible:

Message header

The JMS message header pre-defines several fields for identifying and sending messages between the client and the JMS provider, with the precompiled header as follows:

–jmsdestination
–jmsdeliverymode
–jmsmessageid
–jmstimestamp
–jmscorrelationid
–jmsreplyto
–jmsredelivered
–jmstype
–jmsexpiration
–jmspriority

Message properties

We can set custom properties for messages that are primarily provided to the application. Message properties are useful for implementing message filtering, and the JMS API defines a number of standard properties that a JMS service provider can selectively provide in some standard properties.

Message body

In the message body, the JMS API defines five types of message formats, allowing us to send and receive messages in different forms and to provide compatibility with existing message formats. The different message types are as follows:

text message : Javax.jms.TextMessage, which represents a text object.
Object Message : Javax.jms.ObjectMessage, which represents a Java object.
Bytes message : Javax.jms.BytesMessage, which represents the byte data.
Stream Message : Javax.jms.StreamMessage, which represents the Java raw value data stream.
MAP message : Javax.jms.MapMessage, which represents a key-value pair.

Finally, the following are the providers of common open source JMS services:

    • HornetQ developed by the JBoss community
    • Joram
    • Coridan's Mantaray
    • The OPENJMS of the OPENJMS group
JMS uses the example to implement a JMS point-to-point messaging JMS Publish/Subscribe Messaging example based on the Tomcat + JNDI + ACTIVEMQ link (part modified ~ ~)

http://howtodoinjava.com/jms/jms-java-message-service-tutorial/

The above is the introduction of JMS tutorial, learning Happy ~

Getting Started with the JMS (Java Messaging Service) tutorial

Related Article

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.