ActiveMQ, a message queuing tool commonly used in Java development

1. Introduction
ActiveMQ

Similar products: RabbitMQ, Kafka, Redis (List)

1.1 comparison RabbitMQ
The closest products of the same type are often compared, and their performance can basically replace each other. The main difference is that the two protocols are different. The protocol of RabbitMQ is AMQP (Advanced message queuing Protoco), while ActiveMQ uses JMS(Java Messaging Service) protocol. As the name suggests, JMS is a transport protocol for the Java system. There must be a JVM at both ends of the queue. Therefore, if the development environment is Java, ActiveMQ is recommended. Some Java objects can be used for transmission, such as Map, BLob, Stream, etc. AMQP has strong general lines and is often used in non Java environments. The transmission content is the standard string.

Another point is that RabbitMQ is developed in Erlang. It is troublesome to install the Erlang environment before installation. ActiveMQ decompression is available without any installation.

1.2 comparison KafKa
Kafka has better performance than traditional MQ tools such as ActiveMQ, and the cluster has good scalability.

The disadvantages are:

Repeated messages may occur during transmission,

Sending order is not guaranteed

Some functions of traditional MQ do not, such as the transaction function of messages.

Therefore, Kafka is usually used to process big data logs.

1.3 comparison of Redis
In fact, Redis itself can realize the function of message queue by using List, but there are few functions, and the performance will drop sharply when the queue volume is large. It can be used for scenarios with small amount of data and simple business.

2 install ActiveMQ
Copy apache-activemq-5.14.4-bin.tar.gz to / opt on the Linux server

Unzip tar -zxvf apache-activemq-5.14.4-bin.tar.gz

Rename MV apache-activemq-5.14.4 ActiveMQ

vim /opt/activemq/bin/activemq

View the java environment: vim /etc/profile or echo $JAVA_HOME

Add two lines

JAVA_HOME="/opt/jdk1.8.0_152″

JAVA_CMD="/opt/jdk1.8.0_152/bin"

Registration service

Ln - S / opt / ActiveMQ / bin / ActiveMQ / etc / init.d/activemq (absolute path must be used for soft connection)

chkconfig –add activemq

Prohibited use

cp /opt/activemq/bin/activemq /etc/init.d/activemq

Start service

service activemq start

Shut down service

service activemq stop

Viewing ports through netstat

netstat -tlnp

t: Represents tcp

l: Indicates listening

n: Convert ip and port to domain name and service name

p: Program name displayed

activemq has two important ports. One is the default port for message queuing: 61616

The other is console port 8161

Pass console test

Start consumer

Enter the web console

Account / password default: admin/admin

Click Queues

Observation client

3. Using message queuing in Java
3.1 import dependent coordinates in GMALL service util

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-activemq</artifactId>
   <exclusions>
      <exclusion>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
      </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>org.apache.activemq</groupId>
   <artifactId>activemq-pool</artifactId>
   <version>5.15.2</version>
   <exclusions>
      <exclusion>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
      </exclusion>
   </exclusions>
</dependency>

3.2 add producer in payment project

public class ProducerTest {

public static void main(String[] args) throws JMSException {
    // Create connection factory
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.67.201:61616");
    Connection connection = connectionFactory.createConnection();
    connection.start();
    // When creating a session, the first parameter indicates whether transactions are supported. When false, the second parameter is Session.AUTO_ACKNOWLEDGE auto sign in, Session.CLIENT_ACKNOWLEDGE manual sign in, dups_ OK_ One of them is signed in when you subscribe to acknowledge
    // When the first parameter is set to true, the second parameter can ignore that the server is set to SESSION_TRANSACTED
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    // Create queue
    Queue queue = session.createQueue("Atguigu");

    MessageProducer producer = session.createProducer(queue);
    // Create message object
    ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
    activeMQTextMessage.setText("hello ActiveMq!");
    // send message
    producer.send(activeMQTextMessage);
    producer.close();
    connection.close();
}

}

Note: if there is a transaction, you need to commit the transaction session.commit();

Number Of Pending Messages is the number of messages waiting to be consumed. This is the current number of messages not out of the queue. It can be understood as the total number of received - the total number of outgoing queues

Number Of Consumers this is the Number Of Consumers on the consumer side

Messages Enqueued the total number of messages in the queue, including those out of the queue. This number only increases

Messages Dequeued messages queued can be understood as the quantity consumed by consumers

Summary:

When a message enters the queue, the message waiting to be consumed is 1 and the message entering the queue is 1.
When the message is consumed, the message waiting to be consumed is 0, the message entering the queue is 1, and the message leaving the queue is 1
When a message arrives, the message waiting to be consumed is 1, and the message entering the queue is 2

3.3 add the consumer end in the payment item
public class ConsumerTest {

public static void main(String[] args) throws JMSException {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://192.168.67.201:61616");
    // Create connection
    Connection connection = activeMQConnectionFactory.createConnection();
    connection.start();
    // Create session
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    // Create queue
    Queue queue = session.createQueue("Atguigu");
    // Create Consumer
    MessageConsumer consumer = session.createConsumer(queue);
    // receive messages
    consumer.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            // Parameter is the received message
            if (message instanceof  TextMessage){
                try {
                    String text = ((TextMessage) message).getText();
                    System.out.println(text+"Messages received! ");
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    consumer.close();
    session.close();
}

}

3.4 transaction control
Transaction when producer commits

Transaction on true

Only send will not be submitted to the queue. Only when session.commit() is executed will the message be actually submitted to the queue.

Transaction not enabled false

As long as send is executed, it enters the queue.

Transaction when consumer receives

When the transaction is started, the sign in must be written

Session.SESSION_TRANSACTED

After receiving the message, the message is not really consumed. The message is just locked. Once the thread dies, throws an exception, or the program executes session.rollback(), the message will be released and returned to the queue to be consumed by other consumers again. java training

Transaction is not enabled, sign in method is selected

Session.AUTO_ACKNOWLEDGE

Just call the comsumer.receive method to automatically confirm.

Transaction is not enabled, sign in method is selected

Session.CLIENT_ACKNOWLEDGE

The client needs to execute message.acknowledge(), otherwise it will be regarded as uncommitted. After the thread ends, other threads can receive it.

This method is very similar to the transaction mode, except that it cannot be rolled back manually, and a message can be confirmed separately.

Manual sign in

Transaction is not enabled, sign in method is selected

Session.DUPS_OK_ACKNOWLEDGE

It is used for batch signing in in Topic mode, which can improve the performance. However, in some cases, messages may be submitted repeatedly. Consumers using this mode should be able to handle the problem of repeated submission.

3.5 persistence and non persistence
Set through producer.setDeliveryMode(DeliveryMode.PERSISTENT)

The advantage of persistence is that when activemq goes down, the messages in the message queue will not be lost. Non persistence is lost. But it will consume some performance.

Persistence: when the server goes down, messages still exist.

Non persistent: when the server goes down, the message does not exist.

In zookeeper, there is persistence non persistence.

Tags: Java ActiveMQ

Posted on Mon, 29 Nov 2021 08:34:00 -0500 by therainmaker53