A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute 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:
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:
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.
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:
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:
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:
Destination (Destination)Queueconnectionfactory queueconnfactory = (queueconnectionfactory) initialctx.lookup ("primaryQCF"); Queue Purchasequeue = (queue) Initialctx.lookup ("purchase_queue"); Queue Returnqueue = (queue) Initialctx.lookup ("return_queue");
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
JMS ConnectionTopicsession ses = con.createtopicsession (false, session.auto_acknowledge); Get the Topic object Topic t = (Topic) ctx.lookup ("myTopic"); Create TopicSubscriber topicsubscriber receiver = Ses.createsubscriber (t);
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:
JMS Sessions (session)Connection.close ();
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.
JMS message ProducerSession session = Connection.createsession (false, session.auto_acknowledge);
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:
JMS Message ConsumerProducer.send (message);
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;
JMS Message ListenerMessageconsumer consumer = Session.createconsumer (dest); Messageconsumer consumer = Session.createconsumer (queue); Messageconsumer consumer = Session.createconsumer (topic);
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
JMS message StructureListener MyListener = new Listener (); consumer.setmessagelistener (mylistener);
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:
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:
Getting started with the JMS (java messaging Service) Tutorial
Start building with 50+ products and up to 12 months usage for Elastic Compute Service