ActiveMQ learning note 1 - getting started

1 Introduction to ActiveMQ

1.1 support multi language and protocol convenient client.
Languages: java, python, C, C + +, php, etc
Application protocols: OpenWrite, Stomp REST, XMPP, AMQP, etc
1.2 support for spring;
1.3 it supports high-speed message persistence through JDBC and journal, which can be saved in relational database and memory File database.
1.4 support cluster, client server, point-to-point
1.5 support integration with Ajax, etc

2. Installation of ActiveMQ

Official website: http://activemq.apache.org/
2.1 windows installation

reference resources:
https://www.cnblogs.com/hanxiaohui/p/9425191.html
I'm installing on linux, so I'll skip it here.
2.2 linux Installation

reference resources:
https://www.jianshu.com/p/660d998b0b33

3. Getting started Demo

I use java project to implement Demo, or Maven project;

Create a java project

To import packages that ActiveMQ locks depend on:


3.2 implementation of PTP mode

Producer Code:

package com.jzt.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author sj
 */
public class TextProducer {
    public static String MQ_NAME = "admin";

    public static String MQ_PASSWORD = "admin";

    public static String MQ_BROKETURL = "tcp://192.168.106.131:61616";

    public static void main(String[] args) throws JMSException {

        //Connection factory
        ConnectionFactory factory;
        // Connection instance
        Connection connection = null;
        //conversation
        Session session = null;
        // Message sending destination address
        Destination destination;
        // Message Creator
        MessageProducer messageProducer = null;

        try{
            factory = new ActiveMQConnectionFactory(MQ_NAME, MQ_PASSWORD, MQ_BROKETURL);
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("queue");
            messageProducer = session.createProducer(destination);
            for (int i = 0; i < 3; i++){
                TextMessage textMsg = session.createTextMessage("This is the first" + i + "Messages");
                messageProducer.send(textMsg);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            messageProducer.close();
            session.close();
            connection.close();
        }

    }
}

Consumer code:

package com.jzt.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author sj
 */
public class TextConsumer {
    public static String MQ_NAME = "admin";
    public static String MQ_PASSWORD = "admin";
    public static String MQ_BROKETURL = "tcp://192.168.106.131:61616";

    public static void main(String[] args) {
        ConnectionFactory factory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageConsumer messageConsumer = null;
        try{
            factory = new ActiveMQConnectionFactory(MQ_NAME, MQ_PASSWORD, MQ_BROKETURL);
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("queue");
            messageConsumer = session.createConsumer(destination);
            //Method 1, receive through the receive() method
//            int i = 0;
//            while (true) {
//                 //Set the time when the receiver receives the message. If the parameter is empty, it means that the receiver will wait until the message is received
//                 TextMessage message = (TextMessage) messageConsumer.receive();
//                 if (null != message) {
//                     i++;
//                     System.out.println("received message" + i +":"+ message.getText());
//                 } else {
//                     break;
//                }
//            }
            //Mode 2: through the MessageListener listener
            /*
            Asynchronous non blocking mode listener (onMessage)
            The subscriber or consumer registers the message listener setMessageListener with the consumer through the created consumer object,
            When there is a message in the message, the system will automatically call the onMessage method of MessageListener class
            We only need to judge the message type in onMessage method to get the message
             */
            messageConsumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    if (null != message && message instanceof  TextMessage){
                        TextMessage textMessage = (TextMessage) message;
                        try {
                            System.out.println(textMessage.getText());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            /*
                Here's the console stay active
                If there is no such code, when the listener has not listened to the message and the consumer thread has ended, the subsequent close() method will close the resource, resulting in the failure to get the message.
             */
            System.in.read();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                messageConsumer.close();
                session.close();
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

Start the producer and view the ActiveMQ console:

Launch consumer, view console:

be careful:

There are two ways to receive messages: one is through the receive() method, and the other is through the listcenter listener.

Description of two ways to receive messages:

Synchronous blocking (receive):

The message is received through the receive() method of MessageConsumer. When the message is not received or within the specified expiration time, it will be blocked;

Asynchronous non blocking (listener):

Register a message listener through the setmessagelistener of MessageConsumer. When the message arrives, the system will automatically call the onMessage(Message message) method of MessageListener.

3.3 Pub & sub mode

Message Publisher:

package com.jzt.queue.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author sj
 */
public class TopicProducer {
    public static String MQ_NAME = "admin";
    public static String MQ_PASSWORD = "admin";
    public static String MQ_BROKETRUL = "tcp://192.168.106.131:61616";

    public static void main(String[] args) {

        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(MQ_NAME, MQ_PASSWORD, MQ_BROKETRUL);
            Connection connection = factory.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination des = session.createTopic("topic");
            MessageProducer producer = session.createProducer(des);
            TextMessage message = session.createTextMessage("hello topic!");
            producer.send(message);

            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

consumer:

package com.jzt.queue.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import javax.management.remote.rmi.RMIConnectionImpl;

/**
 * @author sj
 */
public class TopicConsumer {
    public static String MQ_NAME = "admin";
    public static String MQ_PASSWARD = "admin";
    public static String MQ_BROKETRUL = "tcp://192.168.106.131:61616";
    public static void main(String[] args) {
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageConsumer consumer = null;
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(MQ_NAME, MQ_PASSWARD, MQ_BROKETRUL);
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createTopic("topic");
            consumer = session.createConsumer(destination);
//            consumer.setMessageListener(new MessageListener() {
//                @Override
//                public void onMessage(Message message) {
//                    if (message instanceof  TextMessage){
//                        TextMessage textMessage = (TextMessage) message;
//                        try {
//                            System.out.println(textMessage.getText());
//                        } catch (JMSException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            });
            consumer.setMessageListener(message -> {
                if (message instanceof  TextMessage){
                        TextMessage textMessage = (TextMessage) message;
                        try {
                            System.out.println(textMessage.getText());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
            });
        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
            try {
                consumer.close();
                session.close();
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

    }
}

The publish and subscribe mode needs to start the consumer first and then the producer. Otherwise, the message consumer in front will not consume.

Summary:

Basic steps of JMS development

1) Create a ConnectionFactory;

2) Create JMSConnection through ConnectionFactory

3) Start Connection

4) Create JMSSession through Connection

5) Create message Destination destination through Session

6) Create a MessageProducer or MessageConsumer through Session and set the destination

7) Send or accept messages (receive, listener)

8) Close resources

 

Tags: Session Apache Java Database

Posted on Thu, 25 Jun 2020 03:32:39 -0400 by droomagon