Java Message Service (JMS) Tutorial
Java Message Service refers to an API for asynchronous communication between two applications. It provides a set of common interfaces for standard message protocols and message services, including creating, sending, and reading messages, it is used to support JAVA application development. In J2EE, when two applications use JMS for communication, they are not directly connected. Instead, they are connected through a common message sending and receiving service to achieve decoupling, we will introduce it in detail in the next tutorial.
Directory:
- Why JMS?
- Advantages of JMS
- JMS message transmission model
- Receive JMS messages
- JMS Programming Interface
- JMS message structure
Why JMS?
In JAVA, if the two applications do not know each other, or even the two programs may be deployed on different continents, how can they send messages? For example, one application, A, is deployed in India, and the other is deployed in the United States. Then, whenever A triggers an event, B wants to obtain some update information from. Of course, there may be more than one B who is interested in A's update information. There may be N applications similar to B who want to obtain the updated information from.
In this case, JAVA provides the best solution-JMS, which perfectly solves the problems discussed above.
JMS is also applicable to event-based applications, such as chat services. It requires an event publishing mechanism to send messages to all clients connected to the server. Different from RMI, JMS does not need to be sent online. When the server sends a message, it does not matter. When the client goes online, it can ensure that the message sent by the server is received. This is a powerful solution that can handle many common problems in today's world.
Advantages of JMS asynchronous
JMS is inherently asynchronous. When a client obtains a message, it does not need to send a request. The message is automatically sent to an available client.
Reliable
JMS ensures that messages are delivered only once. We have encountered the problem of duplicate message creation, and JMS can help you avoid this problem.
JMS message transmission model
Before the emergence of the jms api, most products use either of the "point-to-point" or "Publish/subscribe" methods for message communication. JMS defines the specifications of the two message sending models, which are independent of each other. Any JMS provider can implement one or two models, which are their own choices. The JMS specification provides a common interface to ensure that the program we write based on the jms api is applicable to any model.
Let's take a closer look at the two message transmission models:
Point-to-Point message transmission model
In the point-to-point message transmission model, an application consists of a message queue, a sender, and a receiver. Each message is sent to a special message queue, which stores all messages sent to it (except the messages consumed and expired by the recipient ). The point-to-point message model has the following features:
- Each message has only one receiver;
- The message sender and receiver are not time-dependent;
- When a message sender sends a message, the message can be obtained no matter the receiver program is not running;
- When the recipient receives the message, it will send a confirmation notification (acknowledgement ).
Publish/subscribe message transmission model
In the publish/subscribe message model, the publisher publishes a message that is delivered to all clients through topics. In this model, publishers and subscribers do not know each other. They are anonymous and can dynamically publish and subscribe to topics. A topic is used to save and transmit messages, and stores messages until the messages are delivered to the client.
The features of the publish/subscribe message model are as follows:
- One message can be delivered to multiple subscribers.
- The publisher and subscriber have a time-dependent relationship. The subscriber can receive messages only after the client creates a subscription, and the subscriber must remain active to receive messages.
To ease such strict time relevance, JMS allows subscribers to create a persistent subscription. In this way, even if the subscriber is not activated (running), it can receive messages from the publisher.
Receive messages
In JMS, the following two methods can be used to receive messages:
Synchronization
If the synchronous method is used to receive messages, the message subscriber calls the receive () method. In receive (), a message does not arrive or the method is blocked until it reaches the specified time until the message is available.
Asynchronous
To receive messages asynchronously, the message subscriber needs to register a message listener, which is similar to an event listener. As long as the message arrives, the JMS service provider will deliver the message by calling the onMessage () of the listener.
JMS Programming Interface
The JMS application consists of the following basic modules:
- Administered objects-Connection Factories and Destination)
- Connection object (Connections)
- Session (Sessions)
- Message producer)
- Message consumer)
- Message Listeners)
JMS management object
Administered objects is a pre-configured JMS object, which is created by the system administrator for the client using JMS. There are mainly two managed objects:
- ConnectionFactory)
- Destination)
The two management objects are created by the JMS system administrator on the Application Server console and stored in the JNDI namespace or the JNDI registry of the Application Server.
ConnectionFactory)
The client uses a connection factory object to connect to the JMS service provider, which creates a connection between the JMS service provider and the client. The JMS client (such as the sender or receiver) searches for and obtains the connection in the JNDI namespace. With this connection, the client can communicate with the destination and send/receive 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)
The destination indicates the destination of the message to be sent and the source of the message received by the client. JMS uses two destinations: queue and topic. 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 QueueReceiver receiver = ses.createReceiver(t);
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 with the JMS provider. If we have a ConnectionFactory object, we can use it to create a connection.
Connection connection = connectionFactory.createConnection();
After the connection is created, You need to close it after the program is used:
connection.close();
JMS Session)
Session is a single-thread context used to produce and consume messages. It can be used to create message producers and consumers.
The Session Object implements the Session interface. After creating a connection, we can use it to create a Session.
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
JMS message producer
The message producer is created by the Session to send messages to the destination. The producer implements the MessageProducer interface. We can create producers for the destination, queue, or topic;
MessageProducer producer = session.createProducer(dest);MessageProducer producer = session.createProducer(queue);MessageProducer producer = session.createProducer(topic);
After creating a message producer, you can use the send method to send messages:
producer.send(message);
JMS message consumer
A message consumer is created by a Session to receive messages sent from the destination. Consumers implement the MessageConsumer interface. We can create consumers for the destination, queue, or 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 of a message. It implements the MessageListener interface, which contains an onMessage method. In this method, you need to define the specific action after the message reaches. By calling the setMessageListener method, we define a message listener for the specified consumer.
Listener myListener = new Listener();consumer.setMessageListener(myListener);
JMS message structure
The JMS client uses the JMS message to communicate with the system. Although the format of the JMS message is simple but flexible, the JMS Message consists of three parts:
Message Header
The JMS message header predefines several fields used to identify and send messages between the client and the JMS provider. The pre-compilation header is as follows:
-JMSDestination
-JMSDeliveryMode
-JMSMessageID
-JMSTimestamp
-JMSCorrelationID
-JMSReplyTo
-JMSRedelivered
-JMSType
-JMSExpiration
-JMSPriority
Message attributes
We can set custom attributes for messages. These attributes are mainly provided to applications. Message attributes are very useful for implementing the message filtering function. The jms api defines some standard attributes, and the JMS service provider can selectively provide some standard attributes.
Message Body
In the message body, the jms api defines five types of message formats, so that we can send and receive messages in different forms, and provide compatibility with existing message formats. Different message types are as follows:
Text message: javax. jms. TextMessage, indicating a Text object.
Object message: javax. jms. ObjectMessage, indicating a JAVA Object.
Bytes message: javax. jms. BytesMessage, which indicates byte data.
Stream message: javax. jms. StreamMessage, which indicates the original java value data Stream.
Map message: javax. jms. MapMessage, which indicates a key-value pair.
At last, the Common Open Source JMS service providers are as follows:
- HornetQ developed by the JBoss community
- Joram
- MantaRay of Coridan
- The OpenJMS Group's OpenJMS
The above is the Getting Started tutorial of JMS. In the next article, I will write some examples of JMS.
Happy Learning ~
Translation Link (some modifications are made, not directly translated ~~) : Http://howtodoinjava.com/jms/jms-java-message-service-tutorial/
This article permanently updates the link address: