JMS full name Java Message Service, Java messaging Service. What we want to learn is ActiveMQ, why learn to run to JMS in Java EE? Can we not learn?

What does the official website say first

Translate the above

Apache ActiveMQ is fast, supports many cross-language clients and protocols, has an easy-to-use enterprise integration pattern and many advanced features, while fully supporting JMS 1.1. Take a look at the characteristics of ActiveMQ. As Java development, JMS has become the best choice of ActiveMQ technical specification.

What is JMS?

The JMS API, designed by Sun and several partner companies, defines a common set of interfaces and associated semantics that allow programs written in the Java programming language to communicate with other messaging implementations. Messaging is a method of communication between software components or applications that allows applications to create, send, receive, and read messages.

Messaging supports loosely coupled distributed communication. The component sends a message to a destination from which the recipient can retrieve the message. However, both sender and receiver need not be available to communicate. In reality, the sender and receiver are in a dark forest, unaware of each other’s existence. The sender and receiver just need to know the message format and destination to use. In this respect, messaging differs from tightly coupled techniques, such as remote method invocation (RMI), which require the application to know the methods of the remote application.

The JMS API enables not only loosely coupled communication, but also:

  • Asynchrony: JMS providers can deliver messages to clients when they arrive; The client does not have to request a message in order to receive it.
  • Reliable: THE JMS API ensures that a message is delivered only once.

To recap: JMS is an application-direct messaging approach that leverages message formats and destinations, and is loosely coupled, asynchronous, and reliable.

JMS architecture

There are two very common patterns for JMS messaging architectures, point-to-point and publish-subscribe, which are described below

Point-to-point messaging

The point-to-point pattern is applied to ensure that each message is consumed by a consumer, the core concept of which is queue. Messages are sent to the queue, and consumers consume messages from the specified queue. The following figure

Some characteristics of point-to-point messaging are as follows

  • There is only one consumer per message
  • The sender and receiver of a message are not time-dependent. The receiver can get the message regardless of whether it is running when the client sends it
  • The recipient acknowledges the message and responds

Usage scenario: Use the point-to-point pattern when each message is guaranteed to be consumed by only one consumer.

Publish/subscribe

This model is based on the concept of topic. A picture is worth a thousand words

Publish/subscribe messaging has the following characteristics

  • Each message can have multiple consumers.
  • Consumers subscribe to specific topics
  • Publishers and subscribers are time-dependent. Clients of a subscribing Topic can only consume messages published after the client creates a subscription, and subscribers must remain active to consume messages.

The JMS API also allows a subscriber to create a persistent subscription, and when the subscriber is inactive (disconnected, for example), the JMS server holds the message for the subscriber and retrieves the persistent message when it becomes active again.

News consumption

JMS messages are asynchronous in nature: there is no basic time dependency between the production and consumption of messages. However, the JMS specification in a more precise sense can be consumed in one of two ways:

  • Synchronous:Subscriber or receiver through the callreceiveMethod explicitly gets the message from the destination. thereceiveMethods can beblockedUntil the message arrives or may time out.
  • asynchronous: Clients can register with consumersMessage listener. Whenever a message arrives at the destination, the JMS provider calls the listener’sonMessage()Method to pass the message.

JMS programming model

The basic components of JMS are as follows

  • JMS managed objects: Connection factories and destinations
  • Connections
  • Sessions
  • Message producers
  • Message consumers
  • Messages

We mainly learn ActiveMQ from here. We should be able to get a glimpse of the whole picture and draw inferiorizations from one example. We don’t need to have a deep understanding of the details. So the above understand English and then combined with the picture to know the message transfer process, not each component one by one.

A brief mention of consumers, instead of the two modes of message consumption mentioned above, here are examples to facilitate understanding.

Blocking mode accepts messages

connection.start();
Message m = consumer.receive();
connection.start();
Message m = consumer.receive(1000); // time out after a second
Copy the code

Asynchronous listeners receive messages

Listener myListener = new Listener();
consumer.setMessageListener(myListener);
connection.start();
Copy the code

The onMessage() method in the Listener is where the consumption logic needs to be implemented

JMS message structure

A JMS message consists of three parts: a header, a message property, and a message body

The message header mainly contains some information describing the message, including timestamp, destination, message ID, etc. Message properties, you can customize some properties to the message, you can attach a selector; The Message body is the object we use directly. JMS provides five formats to choose from: TextMessage, MapMessage, BytesMessage, StreamMessage, ObjectMessage and finally, an identifying Message body without Message content.

Take the most common TextMessage as an example of how to send a message.

TextMessage message = session.createTextMessage();
message.setText(msg_text);     // msg_text is a String
producer.send(message);
Copy the code

Message consumption also needs to be consumed using the same message body

Message m = consumer.receive();
if (m instanceof TextMessage) {
    TextMessage message = (TextMessage) m;
    System.out.println("Reading message: " + message.getText());
} else {
    // Handle error
}
Copy the code

Practical cases

Message producer

package com.work.mq;


import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

** ** ** ** **@descriptionActiveMQ version 5.10.0; * Port Description 8161 is the front-end control page port, and 61616 is the server running port. * Created at: 2021-05-12 11:13 */
public class JmsProduce {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "welcome_into_activemq_world";
    public static void main(String[] args) throws JMSException {
        //1. Create a connection factory with the given URL and the default user name and encoding
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2. Go to the connection factory, get the connection and start the access
        Connection connection = connectionFactory.createConnection();
        connection.start();
        // create a session session. The first session is called transaction/the second session is called sign-in
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // create a destination (Queue or Topic)
        Queue queue = session.createQueue(QUEUE_NAME);
        //5. Create message producers
        MessageProducer messageProducer = session.createProducer(queue);
        messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //6. Send messages using the message producer
        for (int i = 0; i < 3; i++) {
            TextMessage message = session.createTextMessage("MSG ---- Yaoyao Attack -- HP -" + i);
            messageProducer.send(message);
        }
        //7. Close resourcesmessageProducer.close(); session.close(); connection.close(); }}Copy the code

Priming consumer

package com.work.mq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/** ** ** ** ** ** ** ** ** ** ** ** **
public class JmsConsumer {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "welcome_into_activemq_world";
    public static void main(String[] args) throws Exception{
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2. Go to the connection factory, get the connection and start the access
        Connection connection = connectionFactory.createConnection();
        connection.start();
        // create a session session. The first session is called transaction/the second session is called sign-in
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // create a destination (Queue or Topic)
        Queue queue = session.createQueue(QUEUE_NAME);
        //5. Create consumers
        MessageConsumer consumer = session.createConsumer(queue);
        while (true){
            TextMessage message = (TextMessage) consumer.receive();
            if(message ! =null){
                System.out.println("***** consumer receives message:"+message.getText());
            }else {
                break; }}//7. Close resourcesconsumer.close(); session.close(); connection.close(); }}Copy the code

rendering

Emmmm did a lot of damage.

The more I learn, the more I feel weak and weak. I always hold the heart of academic awe and hope to encourage each other. Welcome to VX interactive learning!

VX number: CXYWG1943132157

Please leave a comment 👍🤷♀️