JMS learning one (JMS introduction)

1. What is JMS

1. JMS is the Java Message Service (Java Message Service) application program interface, which is an API for message-oriented middleware (MOM) in the Java platform, which is used to send messages between two applications or in a distributed system. For asynchronous communication. Java Message Service is a platform-independent API, and most MOM providers support JMS.

2. JMS is a set of apis of message services, that is, interface specifications, that is, JMS of JDBC message services of databases.

2. Why learn and use JMS

1. In JAVA, if two applications do not know about each other, and even these two programs may be deployed on different continents, how to 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 updated information of A, and there may be N applications similar to B that want to obtain updated information from A. In this case, JAVA provides the best solution - JMS, which perfectly solves the problems discussed above. JMS is also suitable for event-based applications, such as chat services, which require a mechanism to publish events to send messages to all clients connected to the server. Unlike RMI, JMS does not need to be online when sending a message. The server sends the message, and then ignores it; when the client goes online, it is guaranteed to receive the message sent by the server. This is a very powerful solution to many common problems in the world today.

3. What are the advantages of JMS

1. Asynchronous: JMS is inherently asynchronous. When a client obtains a message, it does not need to actively send a request, and the message will be automatically sent to the available clients.

2. Reliable: JMS guarantees that a message will only be delivered once. Everyone has encountered the problem of duplicate message creation, and JMS can help you avoid this problem, just avoid rather than eliminate it, so in some bad circumstances, there may still be duplicates.

Fourth, the JMS messaging model

Before the advent of the JMS API, most products used either "point-to-point" or "pub/sub" for message communication. JMS defines the specifications for these two messaging models, which are independent of each other. Any JMS provider can implement one or both of these models, it is their 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 these two messaging models in more detail;

1. Peer-to-peer messaging model (P2P)

In the point-to-point messaging model, an application consists of message queues, senders, and receivers. Each message is sent to a special message queue that holds all messages sent to it (except those consumed by the receiver and expired messages).

The peer-to-peer messaging model has the following characteristics:

(1) There is only one receiver for each message (I tested it myself, there can be multiple receivers, but when there are multiple receivers, each receiver can only get a few random pieces of information)

(2) There is no time dependency between the message sender and the message receiver.

(3) When the message sender sends a message, the message can be obtained regardless of whether the receiver program is running or not;

(4) When the receiver receives the message, it will send an acknowledgement notification (acknowledgement).

(5), point-to-point message model diagram:

2. Publish/Subscribe Messaging Model

In the publish/subscribe messaging model, a publisher publishes a message, which is delivered to all clients via a topic. In this model, publishers and subscribers do not know each other, are anonymous and can dynamically publish and subscribe to topics. Topic is mainly used to save and deliver messages, and will keep messages until the message is delivered to the client.

The publish/subscribe message model has the following characteristics:

(1) A message can be delivered to multiple subscribers

(2) Publishers and subscribers are time-dependent. Only when the client creates a subscription can it receive messages, and the subscriber needs to remain active to receive messages.

(3) In order to ease 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 messages from the publisher.

(4) Publish/subscribe message model diagram:

 

 

5. Receiving messages

In JMS, messages can be received in the following two ways:

1. Synchronous mode: If the message is received in the synchronous mode, the message subscriber calls the receive() method. In receive(), the method blocks until a message is available or until the specified time has elapsed.

(1), the destination is Queue

 

consumer = session.createConsumer(queue);  
Message message = consumer.receive(); // Receive synchronously  

 

 

(2), the destination is Destination

 

 
consumer = session.createConsumer(destination);  
 // Receive information synchronously, if it has not been obtained, it will block until the information is received   
Message messages = consumer.receive();  
 

 

2. Asynchronous mode: If the message is received asynchronously, the message subscriber needs to register a message listener, which is similar to the event listener. As long as the message arrives, the JMS service provider will deliver the message by calling the listener's onMessage().

Asynchronous reception is to use the monitoring method:

consumer.setMessageListener(new MessageListener(){  
                    @Override  
                    public void onMessage(Message message) {  
                        TextMessage textMessage = (TextMessage)message;  
                        try {  
                            String value = textMessage.getText();  
                            System.out.println("value: "+value);  
                        } catch (JMSException e) {  
                            // TODO Auto-generated catch block  
                            e.printStackTrace();  
                        }  
                    }  
                });

 

6. JMS programming interface

A JMS application consists of the following basic modules:

1. Administered objects - Connection Factories and Destinations
2. Connections
3. Sessions
4. Message Producers
5. Message Consumers Consumers)
6. Message Listeners

7. JMS management objects

Administered objects are pre-configured JMS objects created by the system administrator for clients using JMS. There are mainly two managed objects:
ConnectionFactory
and Destination.
These two managed objects are managed by The JMS system administrator is created by using the Application Server administrative console and stored in the application server's JNDI namespace or JNDI registry.

8. Connection Factory

The client connects to the JMS service provider using a connection factory object, which creates the connection between the JMS service provider and the client. A JMS client (such as a sender or receiver) will search in the JNDI namespace and get the connection. Using this connection, clients can communicate with destinations, send/receive messages to queues or topics. Let's use an example to understand how to send a message:

9. Destination

The destination specifies the destination to which the message was sent and the source from which the client received the message. JMS uses two kinds of destinations, queues and topics.

10. JMS connection

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

 

// Link factory   
        ActiveMQConnectionFactory connectionFactory = null ;  
         // Link object   
        Connection connection = null ;  
        connectionFactory = new ActiveMQConnectionFactory("admin","admin","tcp://192.168.1.111:61616");  
connection = connectionFactory.createConnection();  
            connection.start();

 

 

 

11. JMS session (Session)

Session is a single-threaded context for producing and consuming messages, and can create message producers and message consumers.
The Session object implements the Session interface, and after creating the connection, we can use it to create a Session.

 

// The first parameter is whether to open the transaction true to open, false to not open the transaction, if it is open, remember to submit it manually  
             // The second parameter indicates the sign-in mode, which is generally used for automatic sign-in and the client's own confirmation of sign-   
            in session = connection. createSession( true , Session.AUTO_ACKNOWLEDGE);  

 

 

12. JMS message producer

 

Message producers are created by Session to send messages to destinations. Producers implement the MessageProducer interface, we can create producers for destinations, queues or topics;

(1), Queue (Queue)

Queue queue = session.createQueue("test_queue" );  
             // Create a message producer for the queue   
            MessageProducer producer = session.createProducer(queue);

 

(2), Destination (Destination)

Destination destination = session.createQueue("test-queue" );  
         // Create a message producer for the destination   
        MessageProducer producer = session.createProducer(destination);  

 

(1) (2) These two methods can only be used in the peer-to-peer message model

(3), topic (Topic)

 

// Create a topic   
      Topic topic = session.createTopic("myTopic.messages" );    
       // Create a message producer for the topic   
      MessageProducer producer = session.createProducer(topic);  

 

 

(3), can only be used in the publish/subscribe message model.

 


   After creating a message producer, you can use the send method to send messages:

// Create message   
                TextMessage message = session.createTextMessage();  
                message.setText( "Test queue message"+ i);  
                 // Send message to destination   
                producer.send(message);  

 

13. JMS message consumers

 

Message consumers are created by the Session to receive messages sent by the destination. Consumers implement the MessageConsumer interface, we can create consumers for destinations, queues or topics;

(1), Queue (Queue)

Queue queue = session.createQueue("test_queue"); // Queue (destination, where consumers consume messages)   
                MessageConsumer consumer = session.createConsumer(queue);    // Message consumer

 

 

(2), Destination (Destination)

// Message destination   
        Destination destination = session.createQueue("test-queue" );  
         // Message consumer   
        MessageConsumer consumer = session.createConsumer(destination);  

 

 

(3), topic (Topic)

 

// Create a topic   
        Topic topic = session.createTopic("myTopic.messages" );   
         // Create a consumer for the topic   
        MessageConsumer consumer = session.createConsumer(topic);

 

 

14. JMS message listener (the method of message monitoring is also the asynchronous reception method of messages)
JMS message listener is the default event handler for messages. It implements the MessageListener interface, which contains an onMessage method, which requires Define the specific action after the message arrives. By calling the setMessageListener method we define a message listener for the specified consumer.

 

(1)、TextMessage

consumer.setMessageListener(new MessageListener(){  
                    @Override  
                    public void onMessage(Message message) {  
                        TextMessage textMessage = (TextMessage)message;  
                        try {  
                            String value = textMessage.getText();  
                            System.out.println("value: "+value);  
                        } catch (JMSException e) {  
                            // TODO Auto-generated catch block  
                            e.printStackTrace();  
                        }  
                    }  
                });

 

 


(2)、ObjectMessage

 

consumer.setMessageListener(new MessageListener(){  
            @Override  
            public void onMessage(Message message){  
                try {  
                TestBean  tbean =(TestBean)((ObjectMessage)message).getObject();  
                System.out.println("tbean: "+tbean);  
                if(null != message) {  
                     System.out.println( "Information 1 received: "+ tbean.getName());  
                }  
                } catch (JMSException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
            }  
        });

 

 

Seven, JMS message structure

The JMS client uses JMS messages to communicate with the system. Although the format of JMS messages is simple, it is very flexible. JMS messages consist of three parts:

1. Message header

The JMS message header predefines several fields for identifying and sending messages between the client and the JMS provider. The precompiled headers are as follows:
JMSDestination : The destination of message sending, mainly refers to Queue and Topic, created by session and produced by production The sender's send method is set.
- J MSDeliveryMode : Delivery mode: There are two persistent mode and non-persistent mode. A persistent message should be delivered "only once at a time", which means that if the JMS provider fails, the message is not lost, it will be delivered again after the server has recovered. A non-persistent message is delivered at most once, which means the server fails and the message is lost forever. It is set by the send method of the message producer by the session wear
- JMSMessageID : The identifier that uniquely identifies each message, generated by the JMS message producer. Set by the send method
JMSTimestamp : A JMS Provider is automatically set when the send() method is called, which is the time difference between when the message was sent and when the consumer actually received it. Set by the client
- JMSCorrelationID : used to connect to another message, a typical application is to connect to the original message in a reply message. In most cases, JMSCorrelationID is used to mark a message as a reply to the previous message identified by JMSMessageID, however, JMSCorrelationID can be any value, not just JMSMessageID. Set by the client
- JMSReplyTo : Provide the destination address of this message reply message, set by the client
-JMSRedelivered : If a client receives a message with the JMSRedelivered attribute set, it means that the client may have received the message earlier, but did not sign for it (acknowledged). If the message is redelivered, JMSRedelivered=true else JMSRedelivered=flase. Set by the JMS Provider
JMSType : the identifier of the message type, set by the client
​​JMSExpiration : the expiration time of the message, equal to the timeToLive value in the send method of the Destination plus the time value of GMT at the time of sending. If the timeToLive value is equal to zero, then JMSExpiration is set to zero, indicating that the message never expires. If, after sending, the message has not been sent to the destination after the message expiration time, the message is purged. Set by the send method
JMSPriority : message priority, ten levels from 0-9, 0-4 are normal messages, 5-9 are urgent messages. JMS does not require the JMS Provider to send messages strictly according to these ten priorities, but it must ensure that urgent messages arrive before ordinary messages, and the default is level 4. The message header of a message set by the send method
has these properties. We can design the message of the message as needed, and send the message to the message service using the send() method of the message producer.

2. Message properties

We can set custom properties on the message, these properties are mainly provided to the application. Message attributes are very useful for implementing message filtering. The JMS API defines some standard attributes, and JMS service providers can optionally provide some standard attributes.

3, informed body

In the message body, the JMS API defines five types of message formats, which allow us to send and receive messages in different forms, and provide compatibility with existing message formats. The different message types are as follows:
Text message : javax.jms.TextMessage, representing a text object.
Object message : javax.jms.ObjectMessage, representing a JAVA object.
Bytes message : javax.jms.BytesMessage, representing byte data.
Stream message : javax.jms.StreamMessage, which represents the java primitive value data stream.
Map message : javax.jms.MapMessage, representing key-value pairs.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325116271&siteId=291194637