JMS (Java Message Service) Usage Guide

introduce

JMS is the Java Message Service application program interface. It is a message-oriented middleware (MOM) API in the Java platform, used to send messages between two applications or in a distributed system. Messages for asynchronous communication. It is a vendor-independent API used to access messaging system messages, similar to JDBC (Java Database Connectivity). In JMS, a message is a type of object in JMS, consisting of two parts: header and message body. The message body carries the application's data or payload.

Main advantages and disadvantages

Advantages of JMS include:

  1. Provides a cross-platform, cross-language way to send and receive messages, thereby enabling asynchronous communication between applications.
  2. Supports multiple messaging modes, including point-to-point, publish/subscribe, etc. You can choose the appropriate mode according to specific business needs.
  3. Provides a reliable message delivery mechanism to ensure that messages can be delivered and processed accurately.
  4. Supports persistent messaging, so even if the sender or receiver of the message fails, the message will not be lost.
  5. Supports transaction processing, multiple operations can be combined into an atomic transaction to ensure data integrity and consistency.

However, JMS also has some disadvantages:

  1. Complex configuration: The configuration of JMS is relatively complex, and you need to be familiar with its API and related concepts to use it correctly.
  2. Performance issues: In high-concurrency scenarios, the performance of JMS may be affected and needs to be optimized and adjusted.
  3. Dependence on middleware: JMS needs to rely on message middleware to achieve message delivery and processing. If the middleware fails or has performance problems, it will affect the normal operation of the entire system.
  4. Does not support direct communication: JMS does not support direct communication between the sender and the receiver and needs to be forwarded through middleware, which may increase the message delivery delay and complexity.
  5. High learning cost: For developers who are not familiar with JMS, the learning cost is high and it takes a certain amount of time and energy to master its usage methods and principles.

JMS core components

JMS implementation components usually include the following parts:

  1. JMS提供者(Provider): It provides the core services of JMS and is responsible for the creation, delivery, storage and management of messages. JMS providers are usually associated with specific messaging middleware implementations, such as ActiveMQ, RabbitMQ, etc.
  2. JMS连接工厂(ConnectionFactory): The connection factory is a class used to create a JMS connection. It contains the information required to connect to the message middleware, such as the address of the message broker, port number, user name and password, etc.
  3. JMS连接(Connection): Connection is the communication bridge between JMS client and message middleware. It provides resources such as network connection, thread pool and session.
  4. JMS会话(Session): Session is a class used to send and receive messages. It provides functions such as creating messages, sending messages, receiving messages and confirming messages. Sessions can be persisted to allow recovery of messages after a system failure.
  5. JMS目的地(Destination): The destination is the destination for the message, which can be a queue or topic. Queues are a point-to-point messaging model, while topics are a publish/subscribe messaging model.
  6. JMS生产者(Producer): Producer is a class used to send messages, it uses a session to create the message and uses a connection to send the message to the destination.
  7. JMS消费者(Consumer): Consumer is a class used to receive messages, it uses a session to create a message consumer and uses a connection to receive messages from the destination.
  8. JMS消息(Message): Message is the core entity in JMS, which includes message headers, attributes and message body. According to different storage structures, messages can be divided into text messages, byte messages and object messages.

These components are the core components of JMS and work together to enable messages to be delivered asynchronously between applications. In actual use, it needs to be configured and used accordingly according to specific business requirements and JMS implementation.

JMS source code parsing process

When parsing JMS source code, you can start from the following aspects:

  1. Message sending and receiving process: JMS message sending and receiving is one of the core functions of the entire system. In source code analysis, you can track the entire process of a message from the sender to the receiver and understand how the message is created, sent and received. Specifically, you can view the implementation details of the message creation method, sending method, and receiving method to understand their working principles and processes.
  2. Serialization and deserialization of messages: In JMS, messages need to be transmitted over the network, so messages need to be serialized and deserialized. In source code analysis, you can view the implementation details of message serialization and deserialization, and understand the serialization protocols and algorithms used.
  3. Persistent storage of messages: In JMS, messages can be stored persistently so that they can still be obtained and processed by the recipient after a system failure or restart. In the source code analysis, you can view the implementation details of the persistent storage of messages and learn about the storage media and data structures used.
  4. Filtering and routing of messages: In JMS, messages can be filtered and routed to different recipients. In source code analysis, you can view the implementation details of message filtering and routing, and understand the working principles and implementation methods of the filters and routers used.
  5. Exception handling: In JMS, exception handling is a very important part. In the source code analysis, you can view the implementation details of exception handling and learn how to handle message sending and receiving under abnormal circumstances.

It should be noted that JMS source code analysis requires certain Java programming experience and basic knowledge, as well as understanding and familiarity with JMS implementation. When analyzing source code, you can combine official documents and other materials for in-depth understanding and learning. At the same time, debugging and testing tools can also be used to assist in understanding and analyzing the behavior and implementation details of the source code.

Message distribution method

There are two main ways for JMS to distribute messages: point-to-point (P2P) and publish/subscribe (Pub/Sub).

  1. Peer-to-Peer (P2P) model: In the peer-to-peer model, messages are distributed to a single consumer. Each message is sent to a specific queue and the receiver reads the message from this queue. A queue can have multiple receivers, but each message can only be consumed by one receiver.
  2. Publish/Subscribe (Pub/Sub) model: In the publish/subscribe model, messages are published to a specific topic, and receivers subscribed to this topic can receive the message. A topic can have multiple publishers and multiple subscribers. Each subscriber can receive messages published by all publishers.

The main difference between these two models is that messages in the point-to-point model can only be consumed by one receiver, while messages in the publish/subscribe model can be received by multiple subscribers. In actual use, you can choose an appropriate model for message distribution based on business needs and usage scenarios.

In JMS, both the sender and the receiver need to send and receive messages through a session. A sender uses a session to create a message and sends the message to a destination (queue or topic) over a connection. Receivers use sessions to create message consumers and receive messages from destinations over connections. After receiving the message, the receiver can perform corresponding processing, such as updating the database, calling other applications, or triggering other operations.

JMS usage steps

The use of JMS includes the following steps:

  1. Create a connection factory: The connection factory is a class used to create connections. It contains the information required to connect to the message middleware. JMS clients use connection factories to create connections.
  2. Create connection: The connection is the communication bridge between the JMS client and the message middleware. Connections can be persistent or non-persistent, depending on your needs.
  3. Create Session : Session is a class used to send and receive messages. Both sender and receiver need to create a session.
  4. Create message: JMS provides three types of messages: text messages, byte messages and object messages. Corresponding message types can be created as needed.
  5. Send message: The sender uses a session to create a message and uses a connection to send the message to the message middleware.
  6. Receive message: The receiver uses a session to create a message consumer and uses a connection to receive messages from the message middleware.
  7. Processing the message: Once the message is received, the message can be processed. The processing method can be to update the database, call other applications or trigger other operations, etc.
  8. Close connection: After completing sending and receiving messages, the connection needs to be closed to release resources.

It should be noted that the usage of JMS can be adjusted accordingly according to the specific implementation. At the same time, the JMS API also provides many advanced functions, such as transaction management, message persistence, message filtering and routing, etc. It can be configured and used accordingly as needed.

JMS guarantees message accuracy

JMS (Java Message Service) ensures the accuracy of messages through the following methods:

  1. Message persistence: JMS provides a mechanism for message persistence, that is, storing messages in reliable storage devices, such as databases or file systems. Persistent messages can still be obtained and processed by the recipient after a system failure or restart. Persistence can ensure the non-loss and reliability of messages.
  2. Transaction management: JMS supports transaction management, that is, operations of sending and receiving messages can be committed or rolled back together. The transaction is successful if both the operations of sending and receiving the message are successful. If one of the operations fails, the transaction fails. The consistency and accuracy of messages can be ensured through transaction management.
  3. Message confirmation mechanism: JMS provides a message confirmation mechanism, that is, the receiver can return a confirmation message to the sender, indicating that the correct message has been received. The sender can wait for a confirmation message or automatically resend the message after a period of time. The accuracy and reliability of messages can be guaranteed through the confirmation mechanism.
  4. Error handling: JMS provides an error handling mechanism, that is, when an error or abnormal situation occurs, JMS can throw an exception or notify the user to handle it accordingly. Users can take appropriate measures based on abnormal situations, such as retrying, rolling back, logging, etc. Error handling improves message accuracy and reliability.

In short, JMS ensures the accuracy and reliability of messages by providing message persistence, transaction management, message confirmation mechanism, error handling mechanism and other methods. In actual use, it is necessary to select the appropriate mechanism for configuration and use based on specific business needs and usage scenarios.

Usage example

Here is a simple JMS usage code example for sending and receiving text messages:

import javax.jms.*;

public class JMSExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 创建连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
            
            // 创建连接
            Connection connection = connectionFactory.createConnection();
            connection.start();
            
            // 创建会话
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            
            // 创建目的地(队列)
            Destination destination = session.createQueue("myQueue");
            
            // 创建消息生产者
            MessageProducer producer = session.createProducer(destination);
            
            // 创建文本消息
            TextMessage message = session.createTextMessage("Hello, JMS!");
            
            // 发送消息
            producer.send(message);
            System.out.println("Message sent: " + message.getText());
            
            // 创建消息消费者
            MessageConsumer consumer = session.createConsumer(destination);
            
            // 接收消息
            Message receivedMessage = consumer.receive();
            System.out.println("Message received: " + ((TextMessage) receivedMessage).getText());
            
            // 关闭连接和会话
            consumer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
    
    
            e.printStackTrace();
        }
    }
}

The above example code uses ActiveMQ as the JMS implementation, creates a connection factory that connects to the ActiveMQ broker, and creates a connection using it. Then, create a session for sending and receiving messages. A queue is created on the session as a destination and a message producer is created. Next, a text message is created and sent to the queue using a producer. Then, a message consumer is created to receive messages from the queue. Finally, the consumer, session, and connection are closed. In actual use, it needs to be configured and used accordingly according to specific business requirements and JMS implementation. At the same time, exceptions and error handling also need to be handled to ensure the stability and reliability of the system.

Insert image description here

Guess you like

Origin blog.csdn.net/zhangzehai2234/article/details/134916070