ActiveMQ Learning Summary - Operational Operation 02

I believe you have a general idea of ActiveMQ through your last blog post.

So this blog will lead you step by step to actually operate our ActiveMQ.

The main contents of this paper are as follows:

1. Introduction of ActiveMQ Terminology and API

2.ActiveMQ Text Message Processing

3.ActiveMQ Object Message Processing

Now that we have to learn how to operate in practice, it's a long time since we know some of its terminology and API usage.

Even if we are bored, we should take a general look at it. I believe you will come back later. Because it's very useful.

 

 

One is the term of ActiveMQ (how can we not write words that make people feel more like a blockhouse?)

1 Destination

Destination, JMS Provider (Message Middleware) is responsible for maintenance of objects used to manage messages.
Message Producer needs to specify Destination to send messages, and MessageReceiver needs to specify Destination.
To receive messages.

 

2 Producer

The Message generator is responsible for sending messages to the destination.

 

3 Consumer | Receiver

Message consumers are responsible for consuming [processing | listening | subscribing] messages from destinations.

 

4 Message

Messages encapsulate the contents of a communication.

 

 

 

Introduction of ActiveMQ API

The following API s are all interface types defined in the javax.jms package

Both are JMS (Java Message Service) standard interface definitions

 

1.ConnectionFactory

Link factory, the type of factory used to create links

2.Connection

Links, used to establish the type of access to ActiveMQ connections, are created by the Link Factory ConnectionFactory

3.Session

Session, a persistent, valid, stateful access, created by a link

4.Destination & Queue

Destination. The message access destination used to describe this visit to ActiveMQ, that is, the specific queue in the ActiveMQ service, is created by the session

  interface Queue extends Destination

5.MessageProducer

Message Generator, Tool for Sending Messages to ActiveMQ Services in a Valid Session, Created by Session

6.MessageConsumer

Message consumer [message subscriber | message processing], in an effective session, the tool used to get messages from ActiveMQ service, is created by the session

7.Message

News. Data carrier objects used by message producers when sending messages to ActiveMQ services or by consumers when obtaining messages from ActiveMQ services. Is the top-level interface of all message types [text message | object message, etc.) that can be created through a session or retrieved from an ActiveMQ service through a session

 

 

 

 

Three ActiveMQ Processing Text Messages

Note: * This case will take producer (message producer) and consumer (message sender) as examples.

 

Preparation:

Make sure your ActiveMQ is on and the ports you depend on are closed (it is recommended to close the firewall service iptables stop directly)

Maven environment

 

1 message producer

1.1 Create module

 

 

1,2 stay POM File addition ActiveMQ Dependence (depending on the individual) ActiveMQ Version Search by Yourself)

 <dependencies>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.9.0</version>
        </dependency>
    </dependencies>

 

1.3 Producers of Writing Messages

package cn.arebirth.mq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQTextProducer {
    
    public void sendTextActiveMQ(String msg) {
        //Define Link Factory
        ConnectionFactory connectionFactory = null;

        //Define Link Objects
        Connection connection = null;

        //Define session
        Session session = null;

        //Destination
        Destination destination = null;

        //Define the sender of the message
        MessageProducer producer = null;

        //Define message
        Message message = null;


        try {
            /**
             * userName:The user name for accessing ActiveMQ service is admin by default.
             * password: Password to access ActiveMQ service, admin by default
             * User names and passwords can be modified through the jetty-ream.properties file in the oonf directory of the ActiveMQ installation directory
             *
             * borkerURL: Access the path address of the ActiveMQ service.
             *  The path structure is: protocol name: // host address: port number
             *  Modifications can be found in the conf/activemq.xml file
             *  It was introduced in the last article.
             */
            connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://169.254.18.20:61616");

            //Creating Link Objects
            connection = connectionFactory.createConnection();

            //Start connection
            connection.start();

            /**
             * Parametric 1: Whether transacted uses transaction optional value: true|false
             *      ture:Set the second parameter variable with the transaction for Session.SESSION_TRANSACTION to be managed by session
             *      false:If you don't use transactions, you can set our parameters.
             *
             * acknowledgeMode:
             * * Session.AUTO_ACKNOWLEDGE:Automatic message validation mechanism
             * * Session.CLIENT_ACKNOWLEDGE:Client Confirmation Mechanism
             * * Session.DUPS_OK_ACKNOWLEDGE:Client Confirmation Message Mechanism with Copies
             The meaning of setting these two parameters here is:
             No transactions are used and commits are automatically confirmed by Session
             * This is not too much to explain here, beginners follow the knock, then slowly understand the principle.
             *
             */
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //To create a destination, the destination name is the name of the queue, which is the name of the place where our message is stored. The consumer of the message needs to access the corresponding queue through this name
            //The name is not fixed
            destination = session.createQueue("hello-mq");

            //The producer who creates the message needs to specify the destination (that is, the Destination Afferent parameters)
            producer = session.createProducer(destination);

            //Create message objects and pass in messages that we need to queue
            message = session.createTextMessage(msg);

            //send message
            producer.send(message);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Recycling Message Sender Resources
            if (producer != null) {
                try {
                    producer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

 

 

2. News consumers

2.1 Create Modules

 

 

 

2,2 Adding ActiveMQ dependencies to POM files (self-searching based on individual ActiveMQ versions)

 <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.9.0</version>
        </dependency>

 

2.3 Consumers who write messages

package cn.arebirth.mq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQTextConsumer {

    public void receiveTextActiveMQ() {
        //Define Link Factory
        ConnectionFactory connectionFactory = null;

        //Define Link Objects
        Connection connection = null;

        //Define session
        Session session = null;

        //Destination
        Destination destination = null;

        //Define the consumer (recipient) of the message
        MessageConsumer consumer = null;

        //Define message
        Message message = null;


        try {
            /**
             * userName:The user name for accessing ActiveMQ service is admin by default.
             * password: Password to access ActiveMQ service, admin by default
             * User names and passwords can be modified through the jetty-ream.properties file in the oonf directory of the ActiveMQ installation directory
             *
             * borkerURL: Access the path address of the ActiveMQ service.
             *  The path structure is: protocol name: // host address: port number
             *  Modifications can be found in the conf/activemq.xml file
             *  It was introduced in the last article.
             */
            connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://169.254.18.20:61616");

            //Creating Link Objects
            connection = connectionFactory.createConnection();

            //Start connection
            connection.start();

            /**
             * Parametric 1: Whether transacted uses transaction optional value: true|false
             *      ture:Set the second parameter variable with the transaction for Session.SESSION_TRANSACTION to be managed by session
             *      false:If you don't use transactions, you can set our parameters.
             *
             * acknowledgeMode:
             * * Session.AUTO_ACKNOWLEDGE:Automatic message validation mechanism
             * * Session.CLIENT_ACKNOWLEDGE:Client Confirmation Mechanism
             * * Session.DUPS_OK_ACKNOWLEDGE:Client Confirmation Message Mechanism with Copies
             The meaning of setting these two parameters here is:
             No transactions are used and commits are automatically confirmed by Session
             * This is not too much to explain here, beginners follow the knock, then slowly understand the principle.
             *
             */
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //To create a destination, the destination name is the name of the queue, which is the name of the place where our message is stored. The consumer of the message needs to access the corresponding queue through this name
            //The name is not fixed
            destination = session.createQueue("hello-mq");

            //The consumer who creates the message needs to specify the destination (that is, the Destination Afferent parameters)
            consumer = session.createConsumer(destination);

            //Create message objects for consumers to receive messages
            message = consumer.receive();

            //Processing message
            String msg = ((TextMessage) message).getText();
            System.out.println("ActiveMQ say:" + msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Recycling Message Receiver Resources
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 

 

3 Test results

Define test classes to test our results!

 

3.1 Define the producer test class

package cn.arebirth.mq;

public class ProducerTest {
    public static void main(String[] args) {
        ActiveMQTextProducer producer = new ActiveMQTextProducer();
        producer.sendTextActiveMQ("Hello,ActiveMQ!");
    }
}

When we have finished executing this code, we open our ActiveMQ control panel (first you need to start your ActiveMQ, as described in the previous article!).

 

 

Next, when we see the content of this picture, we can see how the producer works! (hello-mq our custom queue name!)

 

 

 

 

3.2 Define Consumer Test Class

package cn.arebirth.mq;

public class ConsumerTest {
    public static void main(String[] args) {
        ActiveMQTextConsumer consumer = new ActiveMQTextConsumer();
        consumer.receiveTextActiveMQ();
    }
}

 

The results of the operation are as follows: the results!

 

 

 

 

 

When we look closely at the ActiveMQ console, we will find that,

For every Number Of Pending Message and Message Enqueued produced by producer, +1

Number Of pending Message - 1 Message Dequeued +1

Why? Haha, I believe you have probably guessed or read the meaning of English.

Introduction:

  • Name: The name of the message
  • Number Of Pending Message: Number of messages consumed
  • Number Of Consumers: Number of Consumers
  • Message Enqueued: How many messages are there in the queue
  • Message Dequeued: How many messages consumers consume

 

After tampering with text messages, some people will say that they can only tamper with text?? Wrong, let's do something practical next! (It's not you and me, it's us and the computer -. -)

 

 

Three ActiveMQ Processing Object Messages

With the above foundation for processing text messages, we will easily grasp the ability to process object messages! We will omit some of these steps, and they are similar to those above.

 

Object creation (object message processing, then there must be a data carrier object, we can create one by ourselves.) Producers and consumers need this object!)

package cn.arebirth.pojo;

import java.io.Serializable;

/**
 * Must be serialized!!
 */
public class User implements Serializable {
    private String username;
    private String pwd;
    private String content;

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", pwd='" + pwd + '\'' +
                ", content='" + content + '\'' +
                '}';
    }

    public User() {
    }

    public User(String username, String pwd, String content) {
        this.username = username;
        this.pwd = pwd;
        this.content = content;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

 

2 message producers

2.1 still needs the jar package dependency of pom, if it is still in the original environment, it does not need to add it!

<dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.9.0</version>
        </dependency>

 

2.2 Producers of Writing Messages

package cn.arebirth.mq;

import cn.arebirth.pojo.User;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQObjectProducer {

    public void sendObjectActiveMQ(User user){
        //Define Link Factory
        ConnectionFactory connectionFactory = null;

        //Define Link Objects
        Connection connection = null;

        //Define session
        Session session = null;

        //Destination
        Destination destination = null;

        //Define the sender of the message
        MessageProducer producer = null;

        //Define message
        Message message = null;


        try {
            /**
             * userName:The user name for accessing ActiveMQ service is admin by default.
             * password: Password to access ActiveMQ service, admin by default
             * User names and passwords can be modified through the jetty-ream.properties file in the oonf directory of the ActiveMQ installation directory
             *
             * borkerURL: Access the path address of the ActiveMQ service.
             *  The path structure is: protocol name: // host address: port number
             *  Modifications can be found in the conf/activemq.xml file
             *  It was introduced in the last article.
             */
            connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://169.254.18.20:61616");

            //Creating Link Objects
            connection = connectionFactory.createConnection();

            //Start connection
            connection.start();

            /**
             * Parametric 1: Whether transacted uses transaction optional value: true|false
             *      ture:Set the second parameter variable with the transaction for Session.SESSION_TRANSACTION to be managed by session
             *      false:If you don't use transactions, you can set our parameters.
             *
             * acknowledgeMode:
             * * Session.AUTO_ACKNOWLEDGE:Automatic message validation mechanism
             * * Session.CLIENT_ACKNOWLEDGE:Client Confirmation Mechanism
             * * Session.DUPS_OK_ACKNOWLEDGE:Client Confirmation Message Mechanism with Copies
             The meaning of setting these two parameters here is:
             No transactions are used and commits are automatically confirmed by Session
             * This is not too much to explain here, beginners follow the knock, then slowly understand the principle.
             *
             */
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //To create a destination, the destination name is the name of the queue, which is the name of the place where our message is stored. The consumer of the message needs to access the corresponding queue through this name
            //The name is not fixed
            destination = session.createQueue("hello-mq-obj");

            //The producer who creates the message needs to specify the destination (that is, the Destination Afferent parameters)
            producer = session.createProducer(destination);

            //Create message objects and pass in messages that we need to queue
            message = session.createObjectMessage(user);

            //send message
            producer.send(message);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Recycling Message Sender Resources
            if (producer != null) {
                try {
                    producer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

 

3 News Consumers

3.1 still needs the jar package dependency of pom, if it is still in the original environment, it does not need to add it!

<dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.9.0</version>
        </dependency>

 

3.2 Consumers who write messages

package cn.arebirth.mq;

import cn.arebirth.pojo.User;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ActiveMQObjectConsumer {
    public void receiveObjectActiveMQ() {
        //Define Link Factory
        ConnectionFactory connectionFactory = null;

        //Define Link Objects
        Connection connection = null;

        //Define session
        Session session = null;

        //Destination
        Destination destination = null;

        //Define the consumer (recipient) of the message
        MessageConsumer consumer = null;

        //Define message
        Message message = null;


        try {
            /**
             * userName:The user name for accessing ActiveMQ service is admin by default.
             * password: Password to access ActiveMQ service, admin by default
             * User names and passwords can be modified through the jetty-ream.properties file in the oonf directory of the ActiveMQ installation directory
             *
             * borkerURL: Access the path address of the ActiveMQ service.
             *  The path structure is: protocol name: // host address: port number
             *  Modifications can be found in the conf/activemq.xml file
             *  It was introduced in the last article.
             */
            connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://169.254.18.20:61616");

            //Creating Link Objects
            connection = connectionFactory.createConnection();

            //Start connection
            connection.start();

            /**
             * Parametric 1: Whether transacted uses transaction optional value: true|false
             *      ture:Set the second parameter variable with the transaction for Session.SESSION_TRANSACTION to be managed by session
             *      false:If you don't use transactions, you can set our parameters.
             *
             * acknowledgeMode:
             * * Session.AUTO_ACKNOWLEDGE:Automatic message validation mechanism
             * * Session.CLIENT_ACKNOWLEDGE:Client Confirmation Mechanism
             * * Session.DUPS_OK_ACKNOWLEDGE:Client Confirmation Message Mechanism with Copies
             The meaning of setting these two parameters here is:
             No transactions are used and commits are automatically confirmed by Session
             * This is not too much to explain here, beginners follow the knock, then slowly understand the principle.
             *
             */
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //To create a destination, the destination name is the name of the queue, which is the name of the place where our message is stored. The consumer of the message needs to access the corresponding queue through this name
            //The name is not fixed
            destination = session.createQueue("hello-mq-obj");

            //The consumer who creates the message needs to specify the destination (that is, Destination Afferent parameters)
            consumer = session.createConsumer(destination);

            //Create message objects for consumers to receive messages
            message = consumer.receive();

            //Processing message
            ObjectMessage objectMessage = (ObjectMessage) message;
            User user = (User) objectMessage.getObject();
            System.out.println("ActiveMQ say:" + user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Recycling Message Receiver Resources
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 

 

 

4 Create test classes

4.1 Produce Producer test code

package cn.arebirth.mq;

import cn.arebirth.pojo.User;

public class ProducerTest {
    public static void main(String[] args) {
        ActiveMQObjectProducer producer = new ActiveMQObjectProducer();
        producer.sendObjectActiveMQ(new User("Arebirth","123","Hello,ActiveMQ!"));
    }
}

 

When we have finished executing this code, we open our ActiveMQ control panel (first you need to start your ActiveMQ, as described in the previous article!).

 

You'll see our message added to the queue!

 

4.2 Consumer Consumer Test Code

package cn.arebirth.mq;

public class ConsumerTest {
    public static void main(String[] args) {
        ActiveMQObjectConsumer consumer = new ActiveMQObjectConsumer();
        consumer.receiveObjectActiveMQ();
    }
}

When we execute, the following content will appear! Success!

 

Look at the control panel.

 

 

Is it the same as the last list?

 

 

ps

That's all for this article. I hope you can knock on the code. After all, the code is not visible.~

Keywords: Java Session Apache Jetty xml

Added by magic2goodil on Fri, 11 Oct 2019 16:47:26 +0300