Getting started with the JMS (java messaging Service) Tutorial

Source: Internet
Author: User
Tags event listener message queue

Read Catalogue
    • What is the Java messaging Service
    • Why JMS is required
    • Advantages of JMS
    • JMS Message Delivery model
    • Receiving messages
    • JMS Programming Interface
    • JMS message Structure
    • JMS usage Examples
    • Translation link (partial modification ~ ~)
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.


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:


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.


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:


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

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