watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Preface

Active It's open source , Realized JMS1.1 canonical , message-oriented (MOM) Middleware , Provides efficient 、 Extensible 、 Stable and secure enterprise class messaging .AC-tiveMQ Use Apache Authorization provided , Anyone can modify its implementation code .

ActiveMQ The goal of the design is to provide standard , Message oriented , It can integrate message communication middleware across multiple languages and systems .ActiveMQ Realized JMS Standard and provides many additional features . This article will introduce you in detail ActiveMQ Of API Use .

official account :「 Shallow feathered IT hut 」

1. JMS The concept of ?

「 What is? JMS Well :」

  • JMS---------JAVA    Message    Service

  • JAVA The message service , yes sun The interface provided by the company , It's just a norm , This specification is similar to JDBC It's the same , When used, it needs the current specification to implement the product .

「JMS What can I do :」

  • Be able to publish information to the destination

  • The message can be consumed from the destination

2、 Two communication models

「 The communication concept of queues :」

  • characteristic : When we have multiple consumers in the same queue , The sum of data from multiple consumers is all the data in the original queue

  • The communication model of queue is the most suitable scenario : Flow peak elimination , High concurrency processing

「 The communication model of the topic :」

  • characteristic : When we have multiple consumers in our queue , So the data consumed by multiple consumers is the same

  • Application scenarios of topic consumer communication model : Asynchronous communication between services in microservices

3. MQ Implementation product

「 Realize the product :」

  • ActiveMQ

  • RabbitMQ

  • RockerMQ

  • Kafka( The original intention of this design is to do distributed logging , Later, because of the strict order of the logs , At this time, people use Kafka To do message queuing )

4、JMS A common noun in

「 A common noun :」

  • ActiveMQConnectionFactory: This is a factory that creates connections

  • ConnectionFactory: Connected factories

  • Connection: Connect JAVA Yes MQ A connection to

  • Destination: Destination

  • producer (Producer)

  • consumer (Consumer)

  • Session: conversation ( Every time MQ Is called a session )

  • Queue: queue

  • Topic: The theme

5、 What is message queuing

「 Message queue is simply a place to store temporary data :」

  • producer -----------> On the storage medium

  • consumer -----------> On the storage medium

「 Message queues are similar to express companies :」

  • You can give it to the express company

  • The target can also pick up things from the express company

6. ActiveMQ What is it?

「 meaning :」

  • ActiveMQ It's just one. JMS Implementation product , It can achieve JMS All the functions under

7、ActiveMQ Can do

「 The main role :」

  • Peak elimination of flow

  • Asynchronous communication of modules in microservices

  • Processing high and placing orders

  • Dealing with high concurrency of third-party platforms

  • Assist message table to complete the final consistency of distributed transaction

8、ActiveMQ Installation

「ActiveMQ Installation and configuration :」

 1、 Download from the official website Linux Version of ActiveMQ( The latest version is 5.13.4)
       https://activemq.apache.org/download.html
       2、 Unpack the installation
      tar -zxvf apache-activemq-5.13.4-bin.tar.gz
       3、 To configure ( The default configuration is used here , There is no need to modify )
      vim /usr/lical/activemq-1/conf/activemq.xml
       4、 start-up
      cd /usr/local/activemq-1/bin
./activemq start
      5、 Open the management interface ( The management interface can view and manage all queues and messages )
         http://192.168.1.100:8161
        After successful startup , Can browse  http://localhost:8161/admin/
        Default user name 、 password :admin/admin
        The management interface uses jetty Making containers , If you want to modify the port of the management interface , Can edit ../conf/jetty.xml, Find the following paragraph :
      <bean id="jettyPort" class="org.apache.activemq.web.WebConsolePort" init-method="start">
    <!-- the default port       number for the web console -->
    <property name="host" value="0.0.0.0"/>
    <property name="port" value="8161"/>
     </bean>
        user name / The code is  ../conf/jetty-realm.properties  in , For example, to add an administrator jimmy/123456, Please refer to the following modification :
       1
2
3admin: admin, admin
jimmy: 123456, admin
user: user, user
        notes : There is a small hole in the management interface ,ActiveMQ 5.13.2 And jdk1.8 There's something wrong with compatibility , If you use jdk1.8, The management interface enters Queues Tab time , Occasionally, they report errors , But it doesn't affect the normal sending and receiving of messages , It's just that you can't view the queue from the interface , If that happens , Can be jdk Version down to 1.7, At the same time, it's better to empty data All the data in the directory , Restart again activemq that will do .

9. ActiveMQ Of API Use

「AcatveMQ Of API Use :」

  • The use of queues ( producer )

package com.qy.mq.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.Message;
import javax.jms.*;
/**
 * @Auther: qianyu
 * @Date: 2020/11/04 14:12
 * @Description: producer
 */
public class Producer {
    // The address to be published
    private  static final String PATH="tcp://10.7.182.87:61616";
    //ActiveMQ Under the user name
    private static final String userName="admin";
    //ActiveMQ Next password
    private static final String password="admin";
    public static void main(String[] args) throws JMSException {
        // First step : Create a connected factory
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(userName, password, PATH);
        // Get connections through this factory
        Connection connection = activeMQConnectionFactory.createConnection();
        // The third step : Open this connection
        connection.start();
        // Step four : Create operation MQ This conversation
        /**
         *  The first parameter : Whether to use transactions
         *  The second parameter : Client response mode
         *      The first one is : Auto answer
         *      The second kind : The client answers manually
         */
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // The destination where the message needs to be sent (queue The operation is the queue )
        Destination destination=session.createQueue("wqqq");
        // Producers to produce this news
        // There must be producers
        MessageProducer messageProducer = session.createProducer(destination);
        // Send a lot of messages to the message queue
//        for (int i=0;i<100;i++){
            // Messages that need to be prepared to be sent
//            TextMessage textMessage = session.createTextMessage(" I'm Asahi :"+i);
            // Study the types of messages
          /*  BytesMessage bytesMessage = session.createBytesMessage();
            bytesMessage.setByteProperty("www",new Byte("123"));
            // Then you can send a message
            messageProducer.send(bytesMessage);*/
        // establish map Type of message
        /*MapMessage mapMessage = session.createMapMessage();
        mapMessage.setInt("www1",123);
        messageProducer.send(mapMessage);*/
        ObjectMessage objectMessage = session.createObjectMessage(new User(1, "qianyu", "123"));
        messageProducer.send(objectMessage);
//        }
    }
}

  • The use of queues ( consumer )

package com.qy.mq.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.Serializable;
/**
 * @Auther: qianyu
 * @Date: 2020/11/04 14:13
 * @Description: consumer
 */
public class Consumer {
    // The address to be published
    private  static final String PATH="tcp://10.7.182.87:61616";
    //ActiveMQ Under the user name
    private static final String userName="admin";
    //ActiveMQ Next password
    private static final String password="admin";
    public static void main(String[] args) throws JMSException {
        // First step : Create a connected factory
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(userName, password, PATH);
        // Get connections through this factory
        Connection connection = activeMQConnectionFactory.createConnection();
        // The third step : Open this connection
        connection.start();
        // Step four : Create operation MQ This conversation
        /**
         *  The first parameter : Whether to use transactions
         *  The second parameter : Client response mode
         *      The first one is : Auto answer
         *      The second kind : The client answers manually
         */
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // The destination where the message needs to be sent (queue The operation is the queue )
        Destination destination=session.createQueue("wqqq");
        // Creating our consumers
        MessageConsumer messageConsumer = session.createConsumer(destination);
        // Then you can receive our message
        //Message message = messageConsumer.receive();
        // Receive the message and specify the timeout time
//      Message message = messageConsumer.receive(5000);
        // If you don't receive a message, you don't wait   direct over 了    No more
//      Message message = messageConsumer.receiveNoWait();
        // Given the current path, set the listener
        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
               /* BytesMessage bytesMessage= (BytesMessage) message;
                try {
                    System.out.println(" The data obtained is :"+bytesMessage.getByteProperty("www"));
                } catch (JMSException e) {
                    e.printStackTrace();
                }*/
               /*MapMessage mapMessage= (MapMessage) message;
                try {
                    System.out.println(" The data obtained is :"+mapMessage.getInt("www1"));
                } catch (JMSException e) {
                    e.printStackTrace();
                }*/
               // Test the sending and receiving of object type messages
               ObjectMessage objectMessage= (ObjectMessage) message;
                try {
                    User user = (User) objectMessage.getObject();
                    System.out.println(" The data received is :"+user);
                } catch (JMSException e) {
                    e.printStackTrace();
                }
              /*  // We know it's a string type message
                TextMessage textMessage= (TextMessage) message;
                // Now you can print this message
                try {
                    System.out.println(" consumer 1--- The message received was :"+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }*/
                try {
                    // This sentence means that the client will respond manually
                    message.acknowledge();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

  • The producer of the topic model

package com.qy.mq.topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
 * @Auther: qianyu
 * @Date: 2020/11/04 15:17
 * @Description:
 */
public class Producer {
    // The address to be published
    private  static final String PATH="tcp://10.7.182.87:61616";
    //ActiveMQ Under the user name
    private static final String userName="admin";
    //ActiveMQ Next password
    private static final String password="admin";
    public static void main(String[] args) throws JMSException {
        // First step : Create a connected factory
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(userName, password, PATH);
        // Get connections through this factory
        Connection connection = activeMQConnectionFactory.createConnection();
        // The third step : Open this connection
        connection.start();
        // Step four : Create operation MQ This conversation
        /**
         *  The first parameter : Whether to use transactions
         *  The second parameter : Client response mode
         *      The first one is : Auto answer
         *      The second kind : The client answers manually
         */
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // The destination where the message needs to be sent ( The address of the topic model should be created below )
        Destination destination=session.createTopic("topic222");
        // Producers to produce this news
        // There must be producers
        MessageProducer messageProducer = session.createProducer(destination);
        // Send a lot of messages to the message queue
        for (int i=0;i<100;i++){
            // Messages that need to be prepared to be sent
            TextMessage textMessage = session.createTextMessage(" I'm Asahi :"+i);
            // Then you can send a message
            messageProducer.send(textMessage);
        }
    }
}

  • The consumer of the theme model

package com.qy.mq.topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
 * @Auther: qianyu
 * @Date: 2020/11/04 15:19
 * @Description:
 */
public class Consumer {
    // The address to be published
    private  static final String PATH="tcp://10.7.182.87:61616";
    //ActiveMQ Under the user name
    private static final String userName="admin";
    //ActiveMQ Next password
    private static final String password="admin";
    public static void main(String[] args) throws JMSException {
        // First step : Create a connected factory
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(userName, password, PATH);
        // Get connections through this factory
        Connection connection = activeMQConnectionFactory.createConnection();
        // The third step : Open this connection
        connection.start();
        // Step four : Create operation MQ This conversation
        /**
         *  The first parameter : Whether to use transactions
         *  The second parameter : Client response mode
         *      The first one is : Auto answer
         *      The second kind : The client answers manually
         */
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // The destination where the message needs to be sent (queue The operation is the queue )
        Destination destination=session.createTopic("topic222");
        // Creating our consumers
        MessageConsumer messageConsumer = session.createConsumer(destination);
        // Then you can receive our message
        // Given the current path, set the listener
        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                // We know it's a string type message
                TextMessage textMessage= (TextMessage) message;
                // Now you can print this message
                try {
                    System.out.println(" consumer 1--- The message received was :"+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
                try {
                    message.acknowledge();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

This article is about ActiveMQ This is the end of the introduction , There will be more about ActiveMQ More articles in series , Thank you for your support !

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

If you think that asamura's article will help you , Please search and follow on wechat 「 Shallow feathered IT hut 」 WeChat official account , I'll share my computer information knowledge here 、 Theoretical Technology 、 Tool resources 、 The software is introduced 、 The backend development 、 interview 、 A series of articles, such as thoughts on work and some thoughts on life . What you see and what you get , It's all about life . take your time , Work harder , You and I grew up together ...

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

I set up a technology group , If you want to know more about IT The technology of the industry and the problems in life , Welcome to join the group , Just add my wechat , Note that you can enter the group , We look forward to your participation .

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Previous recommendation

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Thorough understanding | utilize Apache CXF Framework development WebService


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Use it quickly Docker, This article is enough !


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

About using Druid Configuration of database monitoring


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

IntelliJ IDEA Hot deployment tools JRebel The use of the tutorial


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

About Maven, How do I understand and use


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

One article for you to understand Spring Basic use of framework


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Java What we need to pay attention to in generics


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

How to be in Java Create elegant objects to improve program performance


watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Shallow feather

Message area

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Point a praise , Prove that you still love me